Measure execution time with high precision in C/C++
Execution time : The execution time or CPU time of a given task is defined as the time spent by the system executing that task in other way you can say the time during which a program is running.
There are multiple way to measure execution time of a program, in this article i will discuss 5 different way to
measure execution time of a program.
- Using
time()function in C & C++.time() : time() function returns the time since the Epoch(jan 1 1970) in seconds.
Header File : “time.h”
Prototype / Syntax : time_t time(time_t *tloc);
Return Value : On success, the value of time in seconds since the Epoch is returned, on error -1 is returned.Below program to demonstrate how to measure execution time using
time()function.#include <bits/stdc++.h>usingnamespacestd;// A sample function whose time taken to// be measuredvoidfun(){for(inti=0; i<10; i++){}}intmain(){/* Time function returns the time since theEpoch(jan 1 1970). Returned time is in seconds. */time_tstart, end;/* You can call it like this : start = time(NULL);in both the way start contain total time in secondssince the Epoch. */time(&start;);// unsync the I/O of C and C++.ios_base::sync_with_stdio(false);fun();// Recording end time.time(&end;);// Calculating total time taken by the program.doubletime_taken =double(end - start);cout <<"Time taken by program is : "<< fixed<< time_taken << setprecision(5);cout <<" sec "<< endl;return0;}Output:Time taken by program is : 0.000000 sec
- Using
clock()function in C & C++.clock() : clock() returns the number of clock ticks elapsed since the program was launched.
Header File : “time.h”
Prototype / Syntax : clock_t clock(void);
Return Value : On success, the value returned is the CPU time used so far as a clock_t; To get the number of seconds used, divide by CLOCKS_PER_SEC.on error -1 is returned.Below program to demonstrate how to measure execution time using
clock()function.you can also see this#include <bits/stdc++.h>usingnamespacestd;// A sample function whose time taken to// be measuredvoidfun(){for(inti=0; i<10; i++){}}intmain(){/* clock_t clock(void) returns the number of clock tickselapsed since the program was launched.To get the numberof seconds used by the CPU, you will need to divide byCLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical32 bit system. */clock_tstart, end;/* Recording the starting clock tick.*/start =clock();fun();// Recording the end clock tick.end =clock();// Calculating total time taken by the program.doubletime_taken =double(end - start) /double(CLOCKS_PER_SEC);cout <<"Time taken by program is : "<< fixed<< time_taken << setprecision(5);cout <<" sec "<< endl;return0;}Output:Time taken by program is : 0.000001 sec
- using
gettimeofday()function in C & C++.gettimeofday() : The function gettimeofday() can get the time as well as timezone.
Header File : “sys/time.h”.
Prototype / Syntax : int gettimeofday(struct timeval *tv, struct timezone *tz);
The tv argument is a struct timeval and gives the number of seconds and micro seconds since the
Epoch.
struct timeval {
time_t tv_sec; // seconds
suseconds_t tv_usec; // microseconds
};
Return Value : return 0 for success, or -1 for failure.Below program to demonstrate how to measure execution time using
gettimeofday()function.#include <bits/stdc++.h>#include <sys/time.h>usingnamespacestd;// A sample function whose time taken to// be measuredvoidfun(){for(inti=0; i<10; i++){}}intmain(){/* The function gettimeofday() can get the time aswell as timezone.int gettimeofday(struct timeval *tv, struct timezone *tz);The tv argument is a struct timeval and gives thenumber of seconds and micro seconds since the Epoch.struct timeval {time_t tv_sec; // secondssuseconds_t tv_usec; // microseconds}; */structtimeval start, end;// start timer.gettimeofday(&start;, NULL);// unsync the I/O of C and C++.ios_base::sync_with_stdio(false);fun();// stop timer.gettimeofday(&end;, NULL);// Calculating total time taken by the program.doubletime_taken;time_taken = (end.tv_sec - start.tv_sec) * 1e6;time_taken = (time_taken + (end.tv_usec -start.tv_usec)) * 1e-6;cout <<"Time taken by program is : "<< fixed<< time_taken << setprecision(6);cout <<" sec"<< endl;return0;}Output:Time taken by program is : 0.000029 sec
- Using
clock_gettime()function in C & C++.clock_gettime() : The clock_gettime() function gets the current time of the clock specified by clock_id, and puts it into the buffer pointed to by tp.
Header File : “time.h”.
Prototype / Syntax : int clock_gettime( clockid_t clock_id, struct timespec *tp );
tp parameter points to a structure containing atleast the following members :
struct timespec {
time_t tv_sec; //seconds
long tv_nsec; //nanoseconds
};
Return Value : return 0 for success, or -1 for failure.
clock_id : clock id = CLOCK_REALTIME,
CLOCK_PROCESS_CPUTIME_ID, CLOCK_MONOTONIC … etc.
CLOCK_REALTIME : clock that measures real i.e., wall-clock) time.
CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timer from the CPU.
CLOCK_MONOTONIC : High resolution timer that is unaffected by system date changes (e.g. NTP daemons).Below program to demonstrate how to measure execution time using
clock_gettime()function.#include <bits/stdc++.h>#include <sys/time.h>usingnamespacestd;// A sample function whose time taken to// be measuredvoidfun(){for(inti=0; i<10; i++){}}intmain(){/* int clock_gettime( clockid_t clock_id, structtimespec *tp ); The clock_gettime() function getsthe current time of the clock specified by clock_id,and puts it into the buffer pointed to by tp.tpparameter points to a structure containingatleast the following members:struct timespec {time_t tv_sec; // secondslong tv_nsec; // nanoseconds};clock id = CLOCK_REALTIME, CLOCK_PROCESS_CPUTIME_ID,CLOCK_MONOTONIC ...etcCLOCK_REALTIME : clock that measures real (i.e., wall-clock) time.CLOCK_PROCESS_CPUTIME_ID : High-resolution per-process timerfrom the CPU.CLOCK_MONOTONIC : High resolution timer that is unaffectedby system date changes (e.g. NTP daemons). */structtimespec start, end;// start timer.// clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start;);// clock_gettime(CLOCK_REALTIME, &start;);clock_gettime(CLOCK_MONOTONIC, &start;);// unsync the I/O of C and C++.ios_base::sync_with_stdio(false);fun();// stop timer.// clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end;);// clock_gettime(CLOCK_REALTIME, &end;);clock_gettime(CLOCK_MONOTONIC, &end;);// Calculating total time taken by the program.doubletime_taken;time_taken = (end.tv_sec - start.tv_sec) * 1e9;time_taken = (time_taken + (end.tv_nsec - start.tv_nsec)) * 1e-9;cout <<"Time taken by program is : "<< fixed<< time_taken << setprecision(9);cout <<" sec"<< endl;return0;}Output:Time taken by program is : 0.000028 sec
- Using
chrono::high_resolution_clockin C++.chrono : Chrono library is used to deal with date and time. This library was designed to deal with the fact that timers and clocks might be different on different systems and thus to improve over time in terms of precision.chrono is the name of a header, but also of a sub-namespace, All the elements in this header are not defined directly under the std namespace (like most of the standard library) but under the std::chrono namespace.
Below program to demonstrate how to measure execution time using
high_resolution_clockfunction. For detail info on chrono library see this and this#include <bits/stdc++.h>#include <chrono>usingnamespacestd;// A sample function whose time taken to// be measuredvoidfun(){for(inti=0; i<10; i++){}}intmain(){autostart = chrono::high_resolution_clock::now();// unsync the I/O of C and C++.ios_base::sync_with_stdio(false);fun();autoend = chrono::high_resolution_clock::now();// Calculating total time taken by the program.doubletime_taken =chrono::duration_cast<chrono::nanoseconds>(end - start).count();time_taken *= 1e-9;cout <<"Time taken by program is : "<< fixed<< time_taken << setprecision(9);cout <<" sec"<< endl;return0;}Output:Time taken by program is : 0.000024 sec


