Times in MAC OS X

Posted on Updated on

There are two functions to help you calculate the elapsed time on Mac OS X: Microseconds() and UpTime().
Microseconds() returns the value since the computer started up with structure UnsingedWide, UpTime() returns the value with structure AbsoluteTime. Both of these two structures are not good to add or substract, so you sould convert them to double, and then use the values.

for example:

UnsignedWide time1, time2;
Microseconds( &time1);
sleep(3);
Microseconds( &time2);
double timedouble1 = ConvertMicrosecondsToDouble( time1);
double timedouble2 = ConvertMicrosecondsToDouble( time2);
double elapesTime = timedouble2 - timedouble1;

for AbsoluteTime , you can convert to the structure Duration or Nanoseconds by AbsoluteToDuration() and AbsoluteToNanoseconds().
The returned value of AbsoluteToDuration() tells you the number of milliseconds (1000 milliseconds = 1 second) that elapsed since the computer was turned on with structure Duration , which is defined as singed long in MAC OS X and we could use it directly.
AbsoluteToNanoseconds returns the value in nanoseconds with structure Nanoseconds, which couldn’t be used dirctly. There’s also codes to convet it to double.

The simplest way to get elapes time is :


AbsoluteTime currentTime, previousTime;
previousTiime = UpTime();
sleep(3);
currentTime = UpTime();
Duration deltaDuration = AbsoluteDeltaToDuration( previousTime, currentTime);

if you want to get more accurate elapes time:


AbsoluteTime currentTime, previousTime;
previousTiime = UpTime();
sleep(3);
currentTime = UpTime();
Nanoseconds deltaNano = AbsoluteDeltaToNanoseconds( previousTiime, currentTime);
double doubleNano = ConvertNanosecondsToDouble( &deltaNano);

The convertion codes:

double ConvertMicrosecondsToDouble(UnsignedWidePtr microsecondsValue)
{
double twoPower32 = 4294967296.0;
double doubleValue;
double upperHalf = (double)microsecondsValue->hi;
double lowerHalf = (double)microsecondsValue->lo;
doubleValue = (upperHalf * twoPower32) + lowerHalf;
return doubleValue
}


double ConvertNanosecondsToDouble( Nanoseconds *nano)
{
double twoPower32 = 4294967296.0;
double doubleValue;
double upperHalf = (double)nano->hi;
double lowerHalf = (double)nano->lo;
doubleValue = (upperHalf * twoPower32) + lowerHalf;
return doubleValue;
}

References:

  1. http://www.meandmark.com/timing.pdf