简体   繁体   中英

What is the purpose of these time counter refinement statements?

I'm trying to implement a GetTime helper function. It gets the current time, measured in counts, then gets the number of counts per second of the system, so you can get the current time in seconds with its relation.

But after that, there is some improvement code that i dont really get. Why are the last two statements there?

double GetTime()
{

//  Current time value, measured in counts
__int64 timeInCounts;
QueryPerformanceCounter((LARGE_INTEGER *)(&timeInCounts));

// To get the frequency (counts per second) of the performance timer
__int64 countsPerSecond;
QueryPerformanceFrequency((LARGE_INTEGER *)(&countsPerSecond));

double r, r0, r1; 

//  Get the time in seconds with the following relation
r0 = double ( timeInCounts / countsPerSecond );

// There is some kind of acuracy improvement here
r1 = ( timeInCounts - ((timeInCounts/countsPerSecond)*countsPerSecond)) 
                / (double)(countsPerSecond);

r = r0 + r1;

return r;
}

If this is homework you should really mark it with the homework tag.

Run the program in a debugger and examine the values r0 and r1 (or use printf). It should be obvious what the two calculations are doing once you see those values.

Edit 6/18

To keep the calculations simple, let's say countsPerSecond has the value 5 and timeInCounts is 17. The calculation timeInCounts / countsPerSecond divides one __int64 by another __int64 so the result will also be an __int64 . Dividing 17 by 5 gives us the result 3 which is then cast to a double so r0 is set to the value 3.0.

The calculation (timeInCounts/countsPerSecond)*countsPerSecond gives us the value 15 which is then subtracted from timeInCounts giving us the value 2.

If the integer value 2 were divided by the integer value 5 we would get zero. But , the divisor is cast to a double so the integer value 2 is divided by the double value 5.0. This gives us a double result, so r1 is set to 0.4.

Finally r0 and r1 are added together giving the final result 3.4.

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