views:

80

answers:

2

According to the cocoa documentation, timestamp on UIEvent is "the number of seconds since system startup." It's an NSTimeInterval.

I'd like to generate, as efficiently as possible, an equivalent number. Of course, I want to do this where UIEvent don't shine. :-)

+2  A: 

Perhaps you could combine the NSDate method -timeIntervalSinceDate: and the mach framework-based function GetPIDTimeInNanoseconds to get to the same result.

Alex Reynolds
I looked at `GetPIDTimeInNanoseconds` and realized that `mach_absolute_time()` was the place to be. So I wrote the blob of code in my answer above. Thanks.
Dave Peck
A: 

Okay, I did a little digging and here is 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 and return
    return (NSTimeInterval) ((double) absTime / 1000000000.0);
}

This appears to be equivalent to timestamp from UIEvent, which given what mach_absolute_time() does makes a lot of sense.

Dave Peck
Does `AbsoluteToNanoseconds` exist on the iPhone? If so, it'd be easier to use that than the timebase info. If not, I'd suggest dividing the numerator by the denominator (after casting one of them to `NSTimeInterval`) and multiplying by that fraction.
Peter Hosey
Isn't AbsoluteToNanoseconds a Carbon API? I hadn't considered using it... not sure about its availability on the phone.
Dave Peck
Nice one. Good to see this worked on the iPhone.
Alex Reynolds