在C语言中测量时间以毫秒或微秒为单位

3

我正在使用Microsoft Visual Studio 2010。我想要在Windows 7平台上用C语言测量微秒级别的时间。如何做到这一点。

2个回答

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

2

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接