如何获得精确的时间,例如在 Objective-C 中以毫秒为单位? [英] 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?
我需要计算方法调用之间的一些延迟.更具体地说,我想计算 UIScrollView 中的滚动速度.
I need to calculate some delays between method calls. More specifically, I want to calculate the speed of scrolling in an UIScrollView.
推荐答案
NSDate
和 timeIntervalSince*
方法将返回一个 NSTimeInterval
具有亚毫秒精度的双精度值.NSTimeInterval
以秒为单位,但它使用双精度来为您提供更高的精度.
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;
还有许多其他方法可以使用 NSDate
计算此间隔,我建议查看 NSDate
的类文档,该文档位于 NSDate 类参考.
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.
这篇关于如何获得精确的时间,例如在 Objective-C 中以毫秒为单位?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!