iPhone: How to get current milliseconds?

262,813

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);
Share:
262,813

Related videos on Youtube

TheNeil
Author by

TheNeil

Interested in iOS development, music, photography, video games, books, and other typical things.

Updated on September 03, 2020

Comments

  • TheNeil
    TheNeil over 3 years

    What is the best way to get the current system time milliseconds?

  • Kay
    Kay almost 13 years
    But it seems to take double the time needed for [[NSDate date] timeIntervalSince1970]. I measured 0.065ms vs. 0.033ms on 15000 calls.
  • Dan Rosenstark
    Dan Rosenstark over 12 years
    And you'll probably need a -fno-objc-arc if you're using ARC :)
  • AbePralle
    AbePralle over 12 years
    I 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
    BadPirate about 12 years
    Note, you'll need to include the Quartz Framework and #import <Quartz/CABase.h> to make this call.
  • BadPirate
    BadPirate about 12 years
    Whoops - thats import #import <QuartzCore/CAAnimation.h>
  • David H
    David H about 12 years
    static unsigned long getMStime(void) { struct timeval time; gettimeofday(&time, NULL); return (time.tv_sec * 1000) + (time.tv_usec / 1000); }
  • Gabe Johnson
    Gabe Johnson over 11 years
    For those new to Xcode (like me) "include Quartz Framework" means adding it to the set of libraries in "Link Binary With Libraries".
  • Jeremy Brooks
    Jeremy Brooks over 10 years
    Or, 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
    Anthony Mattox over 10 years
    If anyone's looking for this in relation to SpriteKit, the 'current time' in SKScene's update method is indeed the CACurrentMediaTime();
  • Hyndrix
    Hyndrix about 10 years
    Interestingly this works fine on my iPhone 5S and Mac but returns a wrong value on an iPad 3.
  • Steven Lu
    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
    Ege Akpinar almost 10 years
    I'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
    Tomas Andrle almost 10 years
  • Tomas Andrle
    Tomas Andrle almost 10 years
    Source code linked from the page is here: github.com/tylerneylon/moriarty
  • Hot Licks
    Hot Licks over 9 years
    [NSDate timeIntervalSinceReferenceDate] is cheaper. (Though it references a different "epoch" -- if you want 1970 add the constant NSTimeIntervalSince1970.)
  • jason gilbert
    jason gilbert over 9 years
    In 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
    Kris Subramanian about 9 years
    timeIntervalSince1970 is a instance property and not a static method on NSDate. So one would have to still write NSTimeInterval myInterval = [NSDate date].timeIntervalSince1970 !!
  • mojuba
    mojuba almost 9 years
    Beware 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
    Caleb over 8 years
    @KrisSubramanian There's a corresponding dateWithTimerIntervalSince1970 class method.
  • Mihir Oza
    Mihir Oza over 8 years
    for getting into milliseconds CurrentTime = [[NSDate date] timeIntervalSince1970] * 1000;
  • Satyam
    Satyam over 8 years
    @MihirOza, but multiplying with 1000 won't provide accurate milliseconds.
  • Muhammad Shauket
    Muhammad Shauket about 8 years
    it return time in -ve
  • Ozgur Vatansever
    Ozgur Vatansever over 7 years
    There is NSTimeIntervalSince1970 macro which is the fastest.
  • Incinerator
    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
    user924 over 6 years
    it's results in seconds not milliseconds!
  • Pavel Alexeev
    Pavel Alexeev almost 6 years
    Important: CACurrentMediaTime() is not ticking while device is sleeping!
  • Leo Dabus
    Leo Dabus over 5 years
    TimeInterval aka Double has no milliseconds property. Date().timeIntervalSince1970 * 1000
  • Nico Haase
    Nico Haase about 5 years
    Please 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
    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