precise time measurement

Abhishek Thakur picture Abhishek Thakur · Jan 15, 2013 · Viewed 80.5k times · Source

I'm using time.h in C++ to measure the timing of a function.

clock_t t = clock();
someFunction();
printf("\nTime taken: %.4fs\n", (float)(clock() - t)/CLOCKS_PER_SEC);

however, I'm always getting the time taken as 0.0000. clock() and t when printed separately, have the same value. I would like to know if there is way to measure the time precisely (maybe in the order of nanoseconds) in C++ . I'm using VS2010.

Answer

Axel Guilmin picture Axel Guilmin · Apr 11, 2014

C++11 introduced the chrono API, you can use to get nanoseconds :

auto begin = std::chrono::high_resolution_clock::now();

// code to benchmark

auto end = std::chrono::high_resolution_clock::now();
std::cout << std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count() << "ns" << std::endl;

For a more relevant value it is good to run the function several times and compute the average :

auto begin = std::chrono::high_resolution_clock::now();
uint32_t iterations = 10000;
for(uint32_t i = 0; i < iterations; ++i)
{
    // code to benchmark
}
auto end = std::chrono::high_resolution_clock::now();
auto duration = std::chrono::duration_cast<std::chrono::nanoseconds>(end-begin).count();
std::cout << duration << "ns total, average : " << duration / iterations << "ns." << std::endl;

But remember the for loop and assigning begin and end var use some CPU time too.