简体   繁体   中英

Measuring time in mili or microseconds in C Language

I am using Microsoft Visual Studio 2010. I wanted to measure time in micro seconds in C language on windows 7 platform. How can I do that.

The way to get accurate time measurements is via performance counters.

In Windows, you can use QueryPerformanceCounter() and QueryPerformanceFrequency() :

http://msdn.microsoft.com/en-us/library/windows/desktop/ms644904%28v=vs.85%29.aspx

EDIT : Here's a simple example that measures the time needed to sum up from 0 to 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);

Output:

sum = 499999999500000000
Seconds = 0.659352

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM