精确的时间测量

Abh*_*kur 45 c++ visual-studio-2010 ctime c++-chrono

我在C++中使用time.h来测量函数的时间.

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

但是,我总是把时间花在0.0000上.clock()和t单独打印时,具有相同的值.我想知道是否有办法在C++中精确测量时间(可能是纳秒级).我正在使用VS2010.

Axe*_*min 92

C++ 11引入了chrono API,你可以用来获得纳秒:

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;
Run Code Online (Sandbox Code Playgroud)

对于更相关的值,最好多次运行该函数并计算平均值:

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;
Run Code Online (Sandbox Code Playgroud)

但请记住for循环并分配beginendvar也会占用一些CPU时间.

  • 当您仅针对Windows时,`QueryPerformanceFrequency`仍然是更好的选择.实际上,VS11和VS12下的`high_resolution_clock`只是一个提供平庸分辨率的`system_clock`的typdef.仅在VS14中,最近才修复此问题.https://connect.microsoft.com/VisualStudio/feedback/details/719443/c-chrono-headers-high-resolution-clock-does-not-have-high-resolution (9认同)

Con*_*ius 56

我通常使用这个QueryPerformanceCounter功能.

例:

LARGE_INTEGER frequency;        // ticks per second
LARGE_INTEGER t1, t2;           // ticks
double elapsedTime;

// get ticks per second
QueryPerformanceFrequency(&frequency);

// start timer
QueryPerformanceCounter(&t1);

// do something
...

// stop timer
QueryPerformanceCounter(&t2);

// compute and print the elapsed time in millisec
elapsedTime = (t2.QuadPart - t1.QuadPart) * 1000.0 / frequency.QuadPart;
Run Code Online (Sandbox Code Playgroud)


SCh*_*rin 6

以下文字,我完全同意,引用了C++中的优化软件(适用于任何C++程序员) -

如果时间间隔很短,则时间测量可能需要非常高的分辨率.在Windows中,您可以使用 GetTickCountQueryPerformanceCounter函数以毫秒级分辨率.使用CPU中的时间戳计数器可以获得更高的分辨率,该计数器以CPU时钟频率计数.

存在一个问题,"时钟频率可能会动态变化,并且测量因中断和任务切换而不稳定."