views:

6169

answers:

5

Is there an easy way to get a time very precisely? I need to calculate some delays between method calls. More particular, I want to calculate the speed of scrolling in an UIScrollView.

+4  A: 

CFAbsoluteTimeGetCurrent() returns the absolute time as a double value, but I don't know what its precision is -- it might only update every dozen milliseconds, or it might update every microsecond, I don't know.

Adam Rosenfield
Returns the time in seconds, so not ok for TS
Fortega
@Fortega: It returns a double value, not an integer, so it has sub-second accuracy
Adam Rosenfield
It's a double-precision floating-point value though, and does provide sub-millisecond accuracy. A value of 72.89674947369 seconds is not uncommon...
Jim Dovey
+2  A: 

Does this link (dead now) help? It suggests to use timeIntervalSinceReferenceDate which seems to be at least accurate for milliseconds.

schnaader
[NSDate timeIntervalSinceReferenceDate] * 1000 is great!
Thanks
That link is dead now.
Bahadır
Hm... Internet Archive's Wayback Machine also doesn't work, so I edited and marked it as a dead link. For others that seek help on this, the other answers are great, too ;)
schnaader
+13  A: 

NSDate and the timeIntervalSince* methods will return a NSTimeInterval which is a double with sub-millisecond accuracy. NSTimeInterval is in seconds, but it uses the double to give you greater precision.

In order to calculate millisecond time accuracy, you can do:

// Get a current time for where you want to start measuring from
NSDate *date = [NSDate date];

// do work...

// Find elapsed time and convert to milliseconds
// Use (-) modifier to conversion since receiver is earlier than now
NSTimeInterval timePassed_ms = [date timeIntervalSinceNow] * -1000.0;

Documentation on timeIntervalSinceNow can be found here

There are many other ways to calculate this interval using NSDate, and I would recommend looking at the class documentation for NSDate which is found here

Jeff Thompson
+5  A: 

mach_absolute_time() can be used to get precise measurements.

See http://developer.apple.com/qa/qa2004/qa1398.html

Kristopher Johnson