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 (Time Difference) of task:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
#include<iostream> #include<ctime> using namespace std; int main(){ 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; return 0; } |
Output :
1 2 3 4 5 6 |
root@ubuntu:/home/venkatesh/Code/cpp/progs# g++ time_difference.cpp root@ubuntu:/home/venkatesh/Code/cpp/progs# ./a.out CLOCKS_PER_SEC : 1000000 Time Difference : 1.69994 root@ubuntu:/home/venkatesh/Code/cpp/progs# root@ubuntu:/home/venkatesh/Code/cpp/progs# |
Explanation :
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.