Time Difference Calculation in CPP
Calculate Time difference in C and CPP:
We can use clock() function from the ctime library to calculate time difference between the two events.
The function clock_t clock(void) returns the number of clock ticks elapsed since the program was launched.
Program to calculate the Elapsed time of task:
using namespace std;
clock_t begin_time = clock();
cout << "CLOCKS_PER_SEC : " << CLOCKS_PER_SEC << endl;
for(int i=0; i<=1000000000; i++);
cout << "Time Difference : " << (clock()-begin_time) / (double) CLOCKS_PER_SEC <<endl;
root@ubuntu:/home/venkatesh/Code/cpp/progs# g++ time_difference.cpp
CLOCKS_PER_SEC : 1000000
Time Difference : 1.69994
First of all, We are storing the initial time in the begin_time variable using the clock() function.
Then I’m printing the number of clock ticks for the seconds using CLOCKS_PER_SEC . Just for the logging purpose.
In the next line, I’m counting 1000000000, to create some time delay.
Finally, I’m calculating the time difference by subtracting the present time with the begin_time .
Then dividing the resultant value with the CLOCKS_PER_SEC to get the exact elapsed time in the Seconds.