## Microseconds()

The function Microseconds() returns the number of microseconds (1 million microseconds = 1 second) that have elapsed since the computer was turned on. By calling Microseconds() and comparing its result to the last time you called Microseconds(), you can determine how much time has elapsed.

Microseconds() returns its results in an UnsignedWide data structure. This data structure consists of two 32-bit unsigned integer values that the operating system treats as a 64-bit integer. The problem with using the UnsignedWide data structure to calculate the elapsed time is that you must subtract the previous call to Microseconds() from the most recent call. Subtracting two UnsignedWide values is difficult because the UnsignedWide value is split into two components. An easier way to calculate the elapsed time is convert the UnsignedWide value to a double value. To do the conversion take the upper 32 bits and multiply it by the value (2 ^ 32) and add the lower 32 bits.

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; }

After converting the UnsignedWide data structure to a double value, the math becomes easier. Just subtract the two double values to find the elapsed time.

double previousTime; double CalculateElapsedTime(void) { UnsignedWide currentTime; double currentTimeAsDouble; Microseconds(¤tTime); currentTimeAsDouble = ConvertMicrosecondsToDouble(¤tTime); double elapsedTime = currentTimeAsDouble – previousTime; // Convert elapsed time to seconds. double oneMicrosecond = .000001; double elapsedTimeInSeconds = elapsedTime * oneMicrosecond; previousTime = currentTimeAsDouble; return elapsedTimeInSeconds; }

Looking at the code, you can see that I converted the elapsed time from microseconds to seconds. The reason I did this conversion is because I assumed the velocity for moving objects is expressed in units per second. If you want to express the velocity in units per microsecond, you can avoid doing the conversion.