【发布时间】:2011-12-26 16:26:03
【问题描述】:
我正在使用 Microsoft Visual Studio 2010。我想在 Windows 7 平台上用 C 语言测量时间(以微秒为单位)。我该怎么做。
【问题讨论】:
我正在使用 Microsoft Visual Studio 2010。我想在 Windows 7 平台上用 C 语言测量时间(以微秒为单位)。我该怎么做。
【问题讨论】:
获得准确时间测量的方法是通过性能计数器。
在 Windows 中,您可以使用 QueryPerformanceCounter() 和 QueryPerformanceFrequency():
http://msdn.microsoft.com/en-us/library/windows/desktop/ms644904%28v=vs.85%29.aspx
编辑:这是一个简单的示例,用于测量从 0 到 1000000000 的总和所需的时间:
LARGE_INTEGER frequency;
LARGE_INTEGER start;
LARGE_INTEGER end;
// Get the frequency
QueryPerformanceFrequency(&frequency);
// Start timer
QueryPerformanceCounter(&start);
// Do some work
__int64 sum = 0;
int c;
for (c = 0; c < 1000000000; c++){
sum += c;
}
printf("sum = %lld\n",sum);
// End timer
QueryPerformanceCounter(&end);
// Print Difference
double duration = (double)(end.QuadPart - start.QuadPart) / frequency.QuadPart;
printf("Seconds = %f\n",duration);
输出:
sum = 499999999500000000
Seconds = 0.659352
【讨论】: