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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With