15

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

5 Answers5

13

[[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.

tidwall
  • 6,881
  • 2
  • 36
  • 47
  • 2
    Not really. `timeIntervalSince1970` returns the time in seconds, while the name `currentTimeMillis()` implies that it returns milliseconds. – Sven Sep 09 '10 at 23:48
10

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

Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
7

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
  • 9,344
  • 4
  • 34
  • 40
  • Right, this is cheaper than `[[NSDate date] timeIntervalSince1970] * 1000`. It return interval from midnight (0 hour) 1/1/1970. You should use `gettimeofday(&t, NULL);` if your code is called very often like update loop on game. You'd beter use long long data type for this big value: `long long millis = t.tv_sec * 1000 + t.tv_usec / 1000;` – hieund Jun 06 '12 at 03:46
2

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
  • 22,475
  • 4
  • 52
  • 71
0

The correct answer is [[NSDate date] timeIntervalSince1970]; this will give you current timestamp in milliseconds.

The answer given by @Noah Witherspoon returns current date but the year is not the current matching year.