Gerrie
Gerrie

Reputation: 806

How to accurately measure time in c++?

I want to measure the execution time of a function very accurately, in picoseconds. Can it be so precise in C++? The methods I currently know to measure time are:

  1. __rdtscp()
  2. std::chrono clock
  3. clock.h clock_t

Does anyone know how accurate these three functions can be? Which one can achieve picosecond time measurement, if all not, is there any way to reduce noise and make time measurement more accurate?

target system is Linux version 4.15.0-122-generic (buildd@lcy01-amd64-010) (gcc version 5.4.0 20160609 (Ubuntu 5.4.0-6ubuntu1~16.04.12)) #124~16.04.1-Ubuntu SMP

Upvotes: 0

Views: 2540

Answers (2)

Howard Hinnant
Howard Hinnant

Reputation: 218750

No clock on a consumer grade computer is going to measure with picosecond accuracy. The call to get the current time alone is going to take at least tens of nanoseconds.

However you can time your target in a loop and measure the entire elapsed time. Then compute the average time per iteration. <chrono> allows you to easily do this and compute the results to picosecond precision:

#include <chrono>
#include <iostream>

int
main()
{
    using picoseconds = std::chrono::duration<long long, std::pico>;
    constexpr auto N = 1000;
    auto t0 = std::chrono::steady_clock::now();
    for (int repeat = 0; repeat < N; ++repeat)
    {
        // measure this
    }
    auto t1 = std::chrono::steady_clock::now();
    auto d = picoseconds{t1 - t0}/N;
    std::cout << d.count() << "ps\n";
}

If you really want to get precise, you can measure the loop overhead (being sure it isn't optimized away), and subtract that off your total prior to averaging.

for (int repeat = 0; repeat < N; ++repeat)
{
    // measure empty loop overhead
    asm volatile("");
}

The syntax for discouraging the optimizer from removing a loop is not portable.

Upvotes: 5

eerorika
eerorika

Reputation: 238351

How to accurately measure time in c++?

Most accurate standard way to measure time is to use std::chrono::high_resolution_clock or std::chrono::steady_clock.

There may exist a more accurate way provided by the system. To find out about that, the first step is to figure out what the target system is.

Does anyone know how accurate these three functions can be?

Depends on implementation and potentially also hardware.

Which one can achieve picosecond time measurement

Probably none of those in practice. The fastest CPU's have cycle times measured in hundreds of pico seconds.

Upvotes: 1

Related Questions