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.
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.
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.
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With