【发布时间】:2013-03-21 04:12:52
【问题描述】:
有没有比 Windows 上的 clock() 函数更好的函数或方法来测量时间?我有一个简短的操作,当我尝试 clock() 或 gettickcount() 时,它说它需要 0.0 秒。我需要一种以毫秒或纳秒为单位来衡量它的方法。
【问题讨论】:
标签: c windows execution-time
有没有比 Windows 上的 clock() 函数更好的函数或方法来测量时间?我有一个简短的操作,当我尝试 clock() 或 gettickcount() 时,它说它需要 0.0 秒。我需要一种以毫秒或纳秒为单位来衡量它的方法。
【问题讨论】:
标签: c windows execution-time
您可以使用QueryPerformanceCounter 和QueryPerformanceFrequency:
#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
int main(void)
{
LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER end;
double interval;
QueryPerformanceFrequency(&frequency);
QueryPerformanceCounter(&start);
// code to be measured
QueryPerformanceCounter(&end);
interval = (double) (end.QuadPart - start.QuadPart) / frequency.QuadPart;
printf("%f\n", interval);
return 0;
}
【讨论】:
interval 应该以秒为单位(根据this answer 和QueryPerformanceFrequency's documentation)
clock() 给出的是挂墙时间而不是执行时间。我尝试了这种 QPC 方法,希望获得一致的时间(用于分析),但遗憾的是这里测量的时间也不同。这是针对 1 秒或更长时间的周期,以及每次运行时完全相同的操作,因此它不能测量执行时间。所以我还是要跑几次,记录最短的时间。
您可以使用QueryPerformanceCounter 结合QueryPerformanceFrequency 来获得纳秒级精度。
【讨论】: