Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I get a precise time, for example in milliseconds in Objective-C?

Is there an easy way to get a time very precisely?

I need to calculate some delays between method calls. More specifically, I want to calculate the speed of scrolling in an UIScrollView.

like image 327
Thanks Avatar asked May 20 '09 18:05

Thanks


People also ask

How do you measure time in milliseconds?

To convert an hour measurement to a millisecond measurement, multiply the time by the conversion ratio. The time in milliseconds is equal to the hours multiplied by 3,600,000.

What is NSTimeInterval?

A NSTimeInterval value is always specified in seconds; it yields sub-millisecond precision over a range of 10,000 years. On its own, a time interval does not specify a unique point in time, or even a span between specific times.


2 Answers

NSDate and the timeIntervalSince* methods will return a NSTimeInterval which is a double with sub-millisecond accuracy. NSTimeInterval is in seconds, but it uses the double to give you greater precision.

In order to calculate millisecond time accuracy, you can do:

// Get a current time for where you want to start measuring from NSDate *date = [NSDate date];  // do work...  // Find elapsed time and convert to milliseconds // Use (-) modifier to conversion since receiver is earlier than now double timePassed_ms = [date timeIntervalSinceNow] * -1000.0; 

Documentation on timeIntervalSinceNow.

There are many other ways to calculate this interval using NSDate, and I would recommend looking at the class documentation for NSDate which is found in NSDate Class Reference.

like image 130
Jeff Thompson Avatar answered Oct 10 '22 05:10

Jeff Thompson


mach_absolute_time() can be used to get precise measurements.

See http://developer.apple.com/qa/qa2004/qa1398.html

Also available is CACurrentMediaTime(), which is essentially the same thing but with an easier-to-use interface.

(Note: This answer was written in 2009. See Pavel Alexeev's answer for the simpler POSIX clock_gettime() interfaces available in newer versions of macOS and iOS.)

like image 40
Kristopher Johnson Avatar answered Oct 10 '22 04:10

Kristopher Johnson