UpTime()

The function UpTime() returns the amount of elapsed time since the computer started up. It returns the elapsed time in an AbsoluteTime data structure, which is a 64-bit integer. You can’t directly do anything with the AbsoluteTime data structure. You must use one of the two conversion functions Apple supplies. The first function is AbsoluteToDuration(), which tells you the number of milliseconds (1000 milliseconds = 1 second) that elapsed since the computer was turned on. The advantage of using the Duration data structure is that the structure is a 32-bit integer. You don’t have to convert it to a double. For games millisecond accuracy is usually sufficient.

double previousTime; 

double CalculateElapsedTime(void) 
{ 
	AbsoluteTime currentTime; 
	Duration currentTimeAsDuration; 

	currentTime = UpTime(); 
	currentTimeAsDuration = AbsoluteToDuration(currentTime);

	double elapsedTime = currentTimeAsDuration – previousTime;

	// Convert elapsed time to seconds.
	double oneMillisecond = .001;
	double elapsedTimeInSeconds = elapsedTime * oneMillisecond;

	previousTime = currentTimeAsDuration;
	return elapsedTimeInSeconds;
}

If you need more accuracy, use the second conversion function, AbsoluteToNanoseconds(). This function reports the number of nanoseconds (1 billion nanoseconds = 1 second) that elapsed since the computer was turned on. To make use of the nanosecond information, you must convert to double like we did with Microseconds().

double ConvertNanosecondsToDouble(Nanoseconds* nanosecondsValue)
{ 
	double twoPower32 = 4294967296.0;
	double doubleValue;

	double upperHalf = (double)nanosecondsValue->hi;
	double lowerHalf = (double)nanosecondsValue->lo;

	doubleValue = (upperHalf * twoPower32) + lowerHalf;
	return doubleValue;
}

After making the conversion you can calculate the elapsed time.

double previousTime;

double CalculateElapsedTime(void)
{
	AbsoluteTime currentTime;
	Nanoseconds currentTimeAsNanoseconds;
	double currentTimeAsDouble;

	currentTime = UpTime();
	currentTimeAsNanoseconds = AbsoluteToNanoseconds(currentTime);
	currentTimeAsDouble = 
		ConvertNanosecondsToDouble(&currentTimeAsNanoseconds);

	double elapsedTime = currentTimeAsDouble – previousTime;

	// Convert elapsed time to seconds.
	double oneNanosecond = .000000001;
	double elapsedTimeInSeconds = elapsedTime * oneNanosecond;

	previousTime = currentTimeAsDouble;
	return elapsedTimeInSeconds;
}

Conclusion

I have some code available to download that I wrote for the book Mac Game Programming. The code uses Microseconds() to calculate the elapsed time. Look at the functions CalculateTimeStep() and ConvertMicrosecondsToDouble() in the file GameApp.cp.

Previous (Microseconds)