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

前端 未结 5 1881
广开言路
广开言路 2021-02-19 03:57

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

相关标签:
5条回答
  • 2021-02-19 04:26

    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.

    0 讨论(0)
  • 2021-02-19 04:35

    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.

    0 讨论(0)
  • 2021-02-19 04:43

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

    0 讨论(0)
  • 2021-02-19 04:47

    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;
    
    0 讨论(0)
  • 2021-02-19 04:48

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

    0 讨论(0)
提交回复
热议问题