Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

precise time measurement

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.

like image 247
Abhishek Thakur Avatar asked Jan 15 '13 12:01

Abhishek Thakur


People also ask

What is the most precise measurement of time?

Atomic clocks use these frequencies — specifically, absorbing and emitting photons at regular intervals to keep time. They are the most accurate clock we have to measure time in seconds. A common kind of atomic clock uses a form of cesium called cesium-133.

What is precision in clock?

If your clock increments its value only once per second, your resolution is also one second. A high resolution does not help you anything if you can't read the clock. Therefore the smallest possible increase of time that can be experienced by a program is called precision.

What tool is used to measure time accurately?

Today, the usual measuring instruments for time are clocks and watches. For highly accurate measurement of time an atomic clock is used. Stop watches are also used to measure time in some sports.


1 Answers

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.

like image 162
Axel Guilmin Avatar answered Sep 19 '22 20:09

Axel Guilmin