iPhone 的高分辨率计时器?
我正在寻找 iPhone 的高分辨率计时代码,以便进行一些性能计时。我想写这样的代码:
HighResolutionTimer* myTimer = [[HighResolutionTimer alloc]init];
[myTimer start];
[self doSomeLengthyOperation];
NSLog( @"doSomeLengthyOperation took %f seconds", [myTimer elapsedTime] );
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
查看 mach/mach_time.h 标头中的 mach_absolute_time() 。
不要使用 NSDate。当 ntp 执行其操作时,NSDate 甚至不能保证偶尔不会倒退。
(设备可能会出现时钟漂移。如果 iOS 设备快速漂移几秒钟,那么当 NTP 纠正这种漂移时,您会看到时钟突然向后倒退几秒钟。对于计时使用来说非常糟糕。mach_time 使用的计数器不曾经被 NTP 纠正过,因此不能倒退,因此对于计时来说要好得多。)
Look into mach_absolute_time() in the mach/mach_time.h header.
Don't use NSDate. NSDate isn't even guaranteed to not go backwards occasionally, when ntp does its thing.
(Devices can have clock drift. If the iOS device drifts fast a few seconds, then when NTP corrects this drift, you will see the clock suddenly go backwards a few seconds. Very bad for timing use. mach_time uses a counter that doesn't ever get corrected by NTP, thus can't go backwards, thus is far better for timing.)
更好的选择是
CACurrentMediaTime()
使用mach_absolute_time()
但将其转换为CFTimeInterval
(即以秒为单位的双精度时间)。A better option is
CACurrentMediaTime()
which usesmach_absolute_time()
but converts it to aCFTimeInterval
(i.e., time in seconds as a double) for you.这是我对使用
mach_absolute_time()
的时钟计时器的回答,基于计算方法 此处显示,以及NSDate
。就准确度而言,它们实际上是相同的。Mach 版本
NSTimeInterval 版本
结果:
请注意,这两个版本的分辨率都非常好。
*如果您查看这篇文章的编辑历史记录,您可以看到使用
float
代替double
的危险!Here's my answer for clock timers using both
mach_absolute_time()
, based on compute method shown here, andNSDate
. The are actually the same in terms of accuracy.Mach version
NSTimeInterval version
Results:
Note the resolution on both of these is really good.
*If you look at the edit history of this post, you can see the danger of using
float
in the place of adouble
!使用
NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]
获取开始时间,然后NSLog(@"Operation take %f秒。", [NSDate timeIntervalSinceReferenceDate] - startTime);
在最后。Use
NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]
to get a start time, and thenNSLog (@"Operation took %f seconds.", [NSDate timeIntervalSinceReferenceDate] - startTime);
at the end.