As programmer, we usually want to measure the speed of our program in time
(seconds). C/C++ provides a useful function in timing. We can use the function
clock_t clock(void);
to get the CPU clock time. The idea is simple. Get the starting and the
ending CPU clock time then divide by constant CLOCKS_PER_SEC defined in
the time.h header file. Don’t forget to put #include <ctime>
or <time.h>.
Source Code
#include <iostream>
#include <ctime>
using namespace std;
int main() {
clock_t start = clock();
// do something
//
clock_t ends = clock();
cout << "Running Time : " << (double) (ends - start) / CLOCKS_PER_SEC << endl;
return 0;
}
Creating a Simple Timer Program
We can modify the program above a little bit so that we can have
a timer program that measures the speed of the program. In order to create
the timer, we should be able to call other program inside our program.
This can be done by this useful function
int system(const char *cmd)
which is declared in stdlib.h. Don’t forget to put #include <cstdlib>
or <stdlib.h>.