[C, C++](EN) Measure code running time by using clock() function

Measure code running time by using clock() function in c or cpp.


Environment and Prerequisite

  • C, C++


Usage and Example

Usage

  • clock(): It is a function in time.h which returns the processor time consumed by the program. We can consider it as processor running time consumed by program
  • clock_t: Return type of clock() function. It involves data type of clock ticks.
  • CLOCKS_PER_SEC: It is a macro which represents clock ticks per second. Its value depends on system. Use this for human-readable time.
#include <stdio.h>
#include <time.h> // include time.h

int main(){

    clock_t start = clock(); // save start time

    // Code Here!!!

    clock_t end = clock(); // save end time

    // Print measured time
    // Unit: second
    // Dividing a count of clock ticks by this expression yields the number of seconds.
    printf("Time: %lf\n", (double)(end - start)/CLOCKS_PER_SEC);

    return 0;
}


Example

  • Measuring nested loop iteration time.
#include <stdio.h>
#include <time.h> // include time.h

#define ITERATION_TIME 100000

int main (){

    clock_t start = clock(); // save start time

    for(int i = 0; i < ITERATION_TIME; ++i){
        for(int j = 0; j < ITERATION_TIME; ++j)
            int do_something;
    }

    clock_t end = clock(); // save end time

    // Print measured time
    // Unit: second
    // Dividing a count of clock ticks by this expression yields the number of seconds.
    printf("Time: %lf\n",(double)(end - start)/CLOCKS_PER_SEC);

}
  • Result
$ g++ practice_board.cpp -o practice_board
$ ./practice_board
Time: 18.825036


Reference