user440096
user440096

Reputation:

Is there an objective-c/iPhone version of currentTimeMillis() from Java?

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

Upvotes: 15

Views: 9112

Answers (5)

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.

Upvotes: 0

tidwall
tidwall

Reputation: 6949

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

Upvotes: 13

Noah Witherspoon
Noah Witherspoon

Reputation: 57139

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

Upvotes: 10

anon
anon

Reputation:

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.

Upvotes: 2

Max Seelemann
Max Seelemann

Reputation: 9364

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;

Upvotes: 7

Related Questions