Generating iPhone UIEvent Timestamps

If you’re an iPhone developer, you’ve no doubt noticed that UIEvent has a timestamp value. According to the documentation, this is the time (in seconds) since system boot.

So what happens when you want to generate an equivalent timestamp somewhere that you’re not using UIEvent?

I did a little digging; here’s what I came up with:

#import <mach/mach.h>
#import <mach/mach_time.h>

+ (NSTimeInterval)timestamp
{
	// get the timebase info -- different on phone and OSX
	mach_timebase_info_data_t info;
	mach_timebase_info(&info);

	// get the time
	uint64_t absTime = mach_absolute_time();

	// apply the timebase info
	absTime *= info.numer;
	absTime /= info.denom;

	// convert nanoseconds into seconds
	return (NSTimeInterval) ((double)absTime / 1000000000.0);
}

This will give you NSTimeIntervals that are meaningfully comparable to those collected from UIEvent instances.