You can also use CFAbsoluteTimeGetCurrent
:
CFAbsoluteTime start = CFAbsoluteTimeGetCurrent();
and to get the number of seconds that have elapsed:
CFTimeInterval elapsed = CFAbsoluteTimeGetCurrent() - start;
Note, the documentation for CFAbsoluteTimeGetCurrent
warns us:
Repeated calls to this function do not guarantee monotonically increasing results. The system time may decrease due to synchronization with external time references or due to an explicit user change of the clock.
This means that if you're unfortunate enough to measure elapsed time when one of these adjustments take place, you can end up with incorrect elapsed time calculation. This caveat also applies to NSDate
and similar functions. To get around this, you can use CACurrentMediaTime
:
CFTimeInterval start = CACurrentMediaTime();
and
CFTimeInterval elapsed = CACurrentMediaTime() - start;
This uses mach_absolute_time
, but avoids some of its complexities outlined in Technical Q&A QA1398.