Search code examples
c++timing

Timing Functions in c++: The most accurate approach


I'd like to time each function in my code. So I have

func1(); 
func2();
func3();

At the moment I'm using

#include <omp.h>
#include <time.h>

double start1=omp_get_wtime();
func1(); 
double end1=omp_get_wtime();
cout<<"\nfunc1 run time :"<<end1-start1<<endl;


double start2=omp_get_wtime();
func2(); 
double end2=omp_get_wtime();
cout<<"\nfunc2 run time :"<<end2-start2<<endl;
...

Question: Is there any better and more accurate way than I'm using to measure run time for each function?


Solution

  • C++ recently (i.e., standard C++11) introduced std::chrono for getting timing information. This is a cross-platform mechanism. See here. If you have a modern compiler, you can use it as follows:

    std::chrono::time_point<std::chrono::system_clock> t;
    t = std::chrono::system_clock::now();
    

    Prior than C++11, C++ did not contain any timing facility and you add to rely on either

    • mechanisms provided by the operating system; on Linux you can use clock_gettime()
    • mechanism provided by the hardware platform (e.g., x86 TSC)

    Which is the most accurate mechanism depends on your specific operating system and hardware platform.