Monday, December 24, 2018

c++ - Best way to get elapsed time in miliseconds in windows


I'm trying to do it using two FILETIMEs, casting them to ULONGLONGs, substracting the ULONGLONGs, and dividing the result by 10000. But it's pretty slow, and I want to know if there is a better way to do it.I use c++ with visual studio 2008 express edition. This is what I'm using:


FILETIME filetime,filetime2;
GetSystemTimeAsFileTime(&filetime);
Sleep(100);
GetSystemTimeAsFileTime(&filetime2);
ULONGLONG time1,time2;
time1 = (((ULONGLONG) filetime.dwHighDateTime) << 32) + filetime.dwLowDateTime;
time2 = (((ULONGLONG) filetime2.dwHighDateTime) << 32) + filetime2.dwLowDateTime;

printf("ELAPSED TIME IN MS:%d",(int)((time2-time1)/10000));

Answer



Use QueryPerformanceCounter.


long long milliseconds_now() {
static LARGE_INTEGER s_frequency;
static BOOL s_use_qpc = QueryPerformanceFrequency(&s_frequency);
if (s_use_qpc) {
LARGE_INTEGER now;
QueryPerformanceCounter(&now);
return (1000LL * now.QuadPart) / s_frequency.QuadPart;

} else {
return GetTickCount();
}
}

// Somewhere else...
// ...
long long start = milliseconds_now();
// ....
long long elapsed = milliseconds_now() - start;

No comments:

Post a Comment

Simple past, Present perfect Past perfect

Can you tell me which form of the following sentences is the correct one please? Imagine two friends discussing the gym... I was in a good s...