13

我正在寻找 iPhone 的高分辨率时序代码,以便进行一些性能时序。我想写这样的代码:

HighResolutionTimer* myTimer = [[HighResolutionTimer alloc]init];
[myTimer start];
[self doSomeLengthyOperation];
NSLog( @"doSomeLengthyOperation took %f seconds", [myTimer elapsedTime] );
4

4 回答 4

26

查看 mach/mach_time.h 头文件中的 mach_absolute_time()。

不要使用 NSDate。当 ntp 做它的事情时, NSDate 甚至不能保证偶尔不会倒退。

(设备可能会有时钟漂移。如果 iOS 设备快速漂移几秒钟,那么当 NTP 纠正这种漂移时,你会看到时钟突然倒退几秒钟。非常不适合计时使用。mach_time 使用的计数器不会曾经被 NTP 纠正过,因此不能倒退,因此对于计时来说要好得多。)

于 2010-08-22T07:50:55.657 回答
16

一个更好的选择是CACurrentMediaTime()为您使用mach_absolute_time()但将其转换为CFTimeInterval(即,以秒为单位的时间作为双精度数)。

于 2012-08-14T07:44:47.403 回答
8

这是我对使用两者的时钟计时器的回答mach_absolute_time(),基于此处显示的计算方法,和NSDate。就准确度而言,它们实际上是相同的。

马赫版本

double machGetClockS()
{
  static bool init = 0 ;
  static mach_timebase_info_data_t tbInfo ;
  static double conversionFactor ;
  if(!init)
  {
    init = 1 ;
    // get the time base
    mach_timebase_info( &tbInfo ) ;
    conversionFactor = tbInfo.numer / (1e9*tbInfo.denom) ; // ns->s
  }

  return mach_absolute_time() * conversionFactor ; // seconds
}

double machGetClockDiffS()
{
  static double lastTime = 0;

  double currentTime = machGetClockS() ;

  double diff = currentTime - lastTime ;

  lastTime = currentTime ; // update for next call

  return diff ; // that's your answer
}

NSTimeInterval 版本

double getClockS()
{
  return [NSDate timeIntervalSinceReferenceDate] ; // NSTimeInterval is always specified in seconds 
}

double getClockDiffS()
{
  static double lastTime = 0 ;

  double currentTime = getClockS() ;

  double diff = currentTime - lastTime ;

  lastTime = currentTime ; // update for next call

  return diff ; // that's your answer
}

结果:

请注意,这两者的分辨率都非常好。

IOS SIMULATOR,运行帧率计数(以毫秒为单位 (*1000.0))

MACH_ABS_TIME / NSTimeIntervals
58.557001 / 58.552980
40.558007 / 40.562987
52.207822 / 52.200019
33.742197 / 33.742011
38.498912 / 38.504004
48.872679 / 48.868001
45.012602 / 45.011997
57.858432 / 57.865977
25.044615 / 25.038004


IPAD 硬件样品:
33.415041 / 33.416033
33.240167 / 33.239007
33.357542 / 33.357978
33.302833 / 33.302009
33.506750 / 33.509016
33.582250 / 33.582985
33.233958 / 33.232987
33.239042 / 33.237994

*如果你查看这篇文章的编辑历史,你可以看到float使用double!

于 2012-09-23T14:58:37.840 回答
5

用于NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]获取开始时间,然后NSLog (@"Operation took %f seconds.", [NSDate timeIntervalSinceReferenceDate] - startTime);在结束时使用。

于 2010-08-22T05:04:30.440 回答