Measure execution time with high precision in C/C++ - GeeksforGeeks

07 Mar, 2019
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 tomeasure 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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* Time function returns the time since the         Epoch(jan 1 1970). Returned time is in seconds. */    time_t start, end;      /* You can call it like this : start = time(NULL);     in both the way start contain total time in seconds      since 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.    double time_taken = double(end - start);    cout << "Time taken by program is : " << fixed         << time_taken << setprecision(5);    cout << " sec " << endl;    return 0;}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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* clock_t clock(void) returns the number of clock ticks       elapsed since the program was launched.To get the number        of seconds used by the CPU, you will need to divide by        CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical       32 bit system.  */    clock_t start, end;      /* Recording the starting clock tick.*/    start = clock();      fun();      // Recording the end clock tick.    end = clock();      // Calculating total time taken by the program.    double time_taken = double(end - start) / double(CLOCKS_PER_SEC);    cout << "Time taken by program is : " << fixed          << time_taken << setprecision(5);    cout << " sec " << endl;    return 0;}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 theEpoch.struct timeval {time_t tv_sec; // secondssuseconds_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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* The function gettimeofday() can get the time as       well as timezone.        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           };    */    struct timeval 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.    double time_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;    return 0;}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; //secondslong 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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* int clock_gettime( clockid_t clock_id, struct      timespec *tp ); 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.tp      parameter points to a structure containing      atleast the following members:         struct timespec {               time_t   tv_sec;        // seconds                long     tv_nsec;       // nanoseconds           };    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).  */    struct timespec 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.    double time_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;    return 0;}Output:Time taken by program is : 0.000028 sec
Using chrono::high_resolution_clock in 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_clock function. For detail info on chrono library see this and this#include <bits/stdc++.h>#include <chrono>using namespace std;    // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    auto start = chrono::high_resolution_clock::now();      // unsync the I/O of C and C++.    ios_base::sync_with_stdio(false);      fun();      auto end = chrono::high_resolution_clock::now();      // Calculating total time taken by the program.    double time_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;    return 0;}Output:Time taken by program is : 0.000024 sec
My Personal Notes
arrow_drop_upSave
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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* Time function returns the time since the         Epoch(jan 1 1970). Returned time is in seconds. */    time_t start, end;      /* You can call it like this : start = time(NULL);     in both the way start contain total time in seconds      since 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.    double time_taken = double(end - start);    cout << "Time taken by program is : " << fixed         << time_taken << setprecision(5);    cout << " sec " << endl;    return 0;}Output:Time taken by program is : 0.000000 sec

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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* Time function returns the time since the         Epoch(jan 1 1970). Returned time is in seconds. */    time_t start, end;      /* You can call it like this : start = time(NULL);     in both the way start contain total time in seconds      since 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.    double time_taken = double(end - start);    cout << "Time taken by program is : " << fixed         << time_taken << setprecision(5);    cout << " sec " << endl;    return 0;}
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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* clock_t clock(void) returns the number of clock ticks       elapsed since the program was launched.To get the number        of seconds used by the CPU, you will need to divide by        CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical       32 bit system.  */    clock_t start, end;      /* Recording the starting clock tick.*/    start = clock();      fun();      // Recording the end clock tick.    end = clock();      // Calculating total time taken by the program.    double time_taken = double(end - start) / double(CLOCKS_PER_SEC);    cout << "Time taken by program is : " << fixed          << time_taken << setprecision(5);    cout << " sec " << endl;    return 0;}Output:Time taken by program is : 0.000001 sec

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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* clock_t clock(void) returns the number of clock ticks       elapsed since the program was launched.To get the number        of seconds used by the CPU, you will need to divide by        CLOCKS_PER_SEC.where CLOCKS_PER_SEC is 1000000 on typical       32 bit system.  */    clock_t start, end;      /* Recording the starting clock tick.*/    start = clock();      fun();      // Recording the end clock tick.    end = clock();      // Calculating total time taken by the program.    double time_taken = double(end - start) / double(CLOCKS_PER_SEC);    cout << "Time taken by program is : " << fixed          << time_taken << setprecision(5);    cout << " sec " << endl;    return 0;}
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 theEpoch.struct timeval {time_t tv_sec; // secondssuseconds_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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* The function gettimeofday() can get the time as       well as timezone.        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           };    */    struct timeval 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.    double time_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;    return 0;}Output:Time taken by program is : 0.000029 sec

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 theEpoch.struct timeval {time_t tv_sec; // secondssuseconds_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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* The function gettimeofday() can get the time as       well as timezone.        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           };    */    struct timeval 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.    double time_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;    return 0;}
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; //secondslong 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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* int clock_gettime( clockid_t clock_id, struct      timespec *tp ); 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.tp      parameter points to a structure containing      atleast the following members:         struct timespec {               time_t   tv_sec;        // seconds                long     tv_nsec;       // nanoseconds           };    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).  */    struct timespec 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.    double time_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;    return 0;}Output:Time taken by program is : 0.000028 sec

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; //secondslong 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>using namespace std;  // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    /* int clock_gettime( clockid_t clock_id, struct      timespec *tp ); 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.tp      parameter points to a structure containing      atleast the following members:         struct timespec {               time_t   tv_sec;        // seconds                long     tv_nsec;       // nanoseconds           };    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).  */    struct timespec 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.    double time_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;    return 0;}
Time taken by program is : 0.000028 sec

Using chrono::high_resolution_clock in 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_clock function. For detail info on chrono library see this and this#include <bits/stdc++.h>#include <chrono>using namespace std;    // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    auto start = chrono::high_resolution_clock::now();      // unsync the I/O of C and C++.    ios_base::sync_with_stdio(false);      fun();      auto end = chrono::high_resolution_clock::now();      // Calculating total time taken by the program.    double time_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;    return 0;}Output:Time taken by program is : 0.000024 sec
My Personal Notes
arrow_drop_upSave
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_clock function. For detail info on chrono library see this and this
#include <bits/stdc++.h>#include <chrono>using namespace std;    // A sample function whose time taken to// be measuredvoid fun(){    for (int i=0; i<10; i++)    {    }}  int main(){    auto start = chrono::high_resolution_clock::now();      // unsync the I/O of C and C++.    ios_base::sync_with_stdio(false);      fun();      auto end = chrono::high_resolution_clock::now();      // Calculating total time taken by the program.    double time_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;    return 0;}
Time taken by program is : 0.000024 sec

Analysis
C Language
C Programs
C++
C++ Programs
CPP
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.
Time Complexity and Space Complexity
Complexity of different operations in Binary tree, Binary Search Tree and AVL tree
Time Complexity of building a heap
Analysis of Algorithms | Big-O analysis
Analysis of different sorting techniques
Arrays in C/C++
Dynamic Memory Allocation in C using malloc(), calloc(), free() and realloc()
std::sort() in C++ STL
Bitwise Operators in C/C++
Multidimensional Arrays in C / C++