tags:

views:

864

answers:

4

The system time function time(0) gives me a resolution of 1 second, right?

Is there a finer-grained function?

I'm using it to determine the time interval between two events.

A line of code would help me greatly. It makes it easier to have something concrete to hang the concept on when I look in the official documentation.

+1  A: 

Did you look for gettimeofday()? That's the main POSIX function for sub-second resolution timing analogous to time().

See Native App Development for the iPhone for an illustration of its use.

Jonathan Leffler
+1  A: 
self.animationTimer = [NSTimer scheduledTimerWithTimeInterval:animationInterval
                       target:self selector:@selector(drawView) userInfo:nil
                       repeats:YES];

That's a snippet from the OpenGL app template. If you're looking for a high resolution timer, it's probably what you need.

melfar
+3  A: 

NSDate has timeIntervalSinceDate: method, which returns double ("sub-millisecond precision over a range of 10,000 years" Apple says).

NSDate *start = [NSDate date];
…
NSTimeInterval duration = [[NSDate date] timeIntervalSinceDate:start];
porneL
do you know how to use that to get the difference between two times?
willc2
use timeIntervalSince1970 and then compare. It's given in seconds, but with many decimal places - so you can multiply by 1000 to get msec, etc...
Ben Gotow
+6  A: 

See CFAbsoluteTimeGetCurrent:

CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
// do something you want to measure
CFAbsoluteTime end = CFAbsoluteTimeGetCurrent();
NSLog(@"operation took %2.5f seconds", end-start);

Should you find CFAbsouteTime too verbose, you can simply use double instead.

zoul
Can you use that in a sentence?
willc2
How would you get intervals of less than a second from that?
willc2
The returned value is a double, simply multiply by 1000 to get milliseconds or multiply by 1e6 to get μs.
zoul
I was getting a 0 result when I left the 'do something' line blank. It turns out the timer can't measure such a small interval. Once I put some statements in between, I got a result. Thanks for putting actual working code instead of referencing a method name or document link. Sometimes the docs are too abstract for me at first.
willc2
I’m so used to that function that at first it did not occur to me why an example would be needed, sorry. Happy hacking!
zoul
It's easy for programmers to forget how many thousands of bits of knowledge they've absorbed over time. For me just in the last 4 months the Apple docs have gone from completely opaque pages of line noise to useful but muddy guides. Some things I get, for the rest I consult Stack Overflow.
willc2