用C语言测量mili或微秒的时间

时间:2011-11-11 01:37:53

标签: c windows-7

我正在使用Microsoft Visual Studio 2010.我想在Windows 7平台上以C语言测量微秒的时间。我怎么能这样做。

2 个答案:

答案 0 :(得分:3)

获得准确时间测量的方法是通过性能计数器。

在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

答案 1 :(得分:2)