iPhone: How to get current milliseconds?
Solution 1
[[NSDate date] timeIntervalSince1970];
It returns the number of seconds since epoch as a double. I'm almost sure you can access the milliseconds from the fractional part.
Solution 2
If you're looking at using this for relative timing (for example for games or animation) I'd rather use CACurrentMediaTime()
double CurrentTime = CACurrentMediaTime();
Which is the recommended way; NSDate
draws from the networked synch-clock and will occasionally hiccup when re-synching it against the network.
It returns the current absolute time, in seconds.
If you want only the decimal part (often used when syncing animations),
let ct = CACurrentMediaTime().truncatingRemainder(dividingBy: 1)
Solution 3
I benchmarked all the other answers on an iPhone 4S and iPad 3 (release builds). CACurrentMediaTime
has the least overhead by a small margin. timeIntervalSince1970
is far slower than the others, probably due to NSDate
instantiation overhead, though it may not matter for many use cases.
I'd recommend CACurrentMediaTime
if you want the least overhead and don't mind adding the Quartz Framework dependency. Or gettimeofday
if portability is a priority for you.
iPhone 4S
CACurrentMediaTime: 1.33 µs/call
gettimeofday: 1.38 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.45 µs/call
CFAbsoluteTimeGetCurrent: 1.48 µs/call
[[NSDate date] timeIntervalSince1970]: 4.93 µs/call
iPad 3
CACurrentMediaTime: 1.25 µs/call
gettimeofday: 1.33 µs/call
CFAbsoluteTimeGetCurrent: 1.34 µs/call
[NSDate timeIntervalSinceReferenceDate]: 1.37 µs/call
[[NSDate date] timeIntervalSince1970]: 3.47 µs/call
Solution 4
In Swift we can make a function and do as follows
func getCurrentMillis()->Int64{
return Int64(NSDate().timeIntervalSince1970 * 1000)
}
var currentTime = getCurrentMillis()
Though its working fine in Swift 3.0 but we can modify and use the Date
class instead of NSDate
in 3.0
Swift 3.0
func getCurrentMillis()->Int64 {
return Int64(Date().timeIntervalSince1970 * 1000)
}
var currentTime = getCurrentMillis()
Solution 5
So far I found gettimeofday
a good solution on iOS (iPad), when you want to perform some interval evaluation (say, framerate, timing of a rendering frame...) :
#include <sys/time.h>
struct timeval time;
gettimeofday(&time, NULL);
long millis = (time.tv_sec * 1000) + (time.tv_usec / 1000);
Related videos on Youtube
TheNeil
Interested in iOS development, music, photography, video games, books, and other typical things.
Updated on September 03, 2020Comments
-
TheNeil over 3 years
What is the best way to get the current system time milliseconds?
-
Kay almost 13 yearsBut it seems to take double the time needed for [[NSDate date] timeIntervalSince1970]. I measured 0.065ms vs. 0.033ms on 15000 calls.
-
Dan Rosenstark over 12 yearsAnd you'll probably need a
-fno-objc-arc
if you're using ARC :) -
AbePralle over 12 yearsI like this too since it's very portable. Note that depending on the OS you might need to use 'long long' instead of a 'long' and likewise cast time.tv_sec to 'long long' before doing the rest of the calculation.
-
BadPirate about 12 yearsNote, you'll need to include the Quartz Framework and #import <Quartz/CABase.h> to make this call.
-
BadPirate about 12 yearsWhoops - thats import #import <QuartzCore/CAAnimation.h>
-
David H about 12 yearsstatic unsigned long getMStime(void) { struct timeval time; gettimeofday(&time, NULL); return (time.tv_sec * 1000) + (time.tv_usec / 1000); }
-
Gabe Johnson over 11 yearsFor those new to Xcode (like me) "include Quartz Framework" means adding it to the set of libraries in "Link Binary With Libraries".
-
Jeremy Brooks over 10 yearsOr, if you're using Xcode 5 and iOS 7: @import QuartzCore.CAAnimation and you don't need to worry about explicitly adding it to the list of libraries.
-
Anthony Mattox over 10 yearsIf anyone's looking for this in relation to SpriteKit, the 'current time' in SKScene's update method is indeed the CACurrentMediaTime();
-
Hyndrix about 10 yearsInterestingly this works fine on my iPhone 5S and Mac but returns a wrong value on an iPad 3.
-
Steven Lu about 10 years+1, While this is obviously very informative and helpful I wouldn't exactly call it great engineering work without seeing some source code ;)
-
Ege Akpinar almost 10 yearsI've been using this method for a while and came to realise it can return an earlier value when you call it after couple of miliseconds (e.g. call it consecutively and you might not end up with an increasing sequence)
-
Tomas Andrle almost 10 years
-
Tomas Andrle almost 10 yearsSource code linked from the page is here: github.com/tylerneylon/moriarty
-
Hot Licks over 9 years
[NSDate timeIntervalSinceReferenceDate]
is cheaper. (Though it references a different "epoch" -- if you want 1970 add the constantNSTimeIntervalSince1970
.) -
jason gilbert over 9 yearsIn order to avoid getting negative numbers I had to cast before the math: int64_t result = ((int64_t)tv.tv_sec * 1000) + ((int64_t)tv.tv_usec / 1000);
-
Kris Subramanian about 9 yearstimeIntervalSince1970 is a instance property and not a static method on NSDate. So one would have to still write NSTimeInterval myInterval = [NSDate date].timeIntervalSince1970 !!
-
mojuba almost 9 yearsBeware of this issue though: bendodson.com/weblog/2013/01/29/ca-current-media-time This clock apparently stops when the device goes to sleep.
-
Caleb over 8 years@KrisSubramanian There's a corresponding
dateWithTimerIntervalSince1970
class method. -
Mihir Oza over 8 yearsfor getting into milliseconds CurrentTime = [[NSDate date] timeIntervalSince1970] * 1000;
-
Satyam over 8 years@MihirOza, but multiplying with 1000 won't provide accurate milliseconds.
-
Muhammad Shauket about 8 yearsit return time in -ve
-
Ozgur Vatansever over 7 yearsThere is
NSTimeIntervalSince1970
macro which is the fastest. -
Incinerator over 6 years@Satyam actually multiplying with 1000 will give you millisecond precision, the TimeInterval returned by
timeIntervalSince1970
is actually a Double with "sub-millisecond precision" according to the docs. -
user924 over 6 yearsit's results in seconds not milliseconds!
-
Pavel Alexeev almost 6 yearsImportant: CACurrentMediaTime() is not ticking while device is sleeping!
-
Leo Dabus over 5 years
TimeInterval
akaDouble
has no milliseconds property.Date().timeIntervalSince1970 * 1000
-
Nico Haase about 5 yearsPlease add some explanation to your code such that others can learn from it - especially if you post an answer to a question that already has a lot of upvoted answers
-
YourMJK about 4 years@ozgur
NSTimeIntervalSince1970
is a constant describing the seconds between 1970-01-01 and the "reference date" (i.e. 2001-01-01), so it is always equal to 978307200