views:

113

answers:

4

I need to time some events in the app I'm working on. In Java i used to be able to call currentTimeMillis() but there doesnt seem to be a version in Objective-c. Is there a way to check there current time without creating a NSDate and then parsing this object everytime i need this information?

Thanks -Code

A: 

To get very cheap very precise time, you can use gettimeofday(), which is a C Function of the BSD kernel. Please read the man page for full details, but here's an simple example:

struct timeval t;
gettimeofday(&t, NULL);

long msec = t.tv_sec * 1000 + t.tv_usec / 1000;
Max Seelemann
+2  A: 

Instead gettimeofday() you could also use [NSDate timeIntervalSinceReferenceDate] (the class method) and do your calculations with that. But they have the same problem: they operate on "wall clock time". That means your measurement can be off if leap seconds are added while your test is running or at the transition between daylight saving time.

You can use the Mach system call mach_absolute_time() on OS X and iOS. With the information returned by mach_timebase_info() this can be converted to nanoseconds.

Sven
+1  A: 

There's also CFAbsoluteTimeGetCurrent(), which will give you the time in double-precision seconds.

Noah Witherspoon
A: 

[[NSDate date] timeIntervalSince1970] * 1000 returns a the same value as currentTimeMillis()

CFAbsoluteTimeGetCurrent() and [NSDate timeIntervalSinceReferenceDate] both return a double starting at Jan 1 2001 00:00:00 GMT.

jojaba
Not really. `timeIntervalSince1970` returns the time in seconds, while the name `currentTimeMillis()` implies that it returns milliseconds.
Sven
@Sven: Very true, I just edited my answer. Thanks
jojaba