适用于iPhone的高分辨率计时器?

时间:2010-08-22 04:57:49

标签: iphone objective-c timer high-resolution

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

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

4 个答案:

答案 0 :(得分:26)

查看mach / mach_time.h标题中的mach_absolute_time()。

不要使用NSDate。当ntp发挥作用时,NSDate甚至不能保证不会偶尔倒退。

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

答案 1 :(得分:16)

更好的选项是CACurrentMediaTime(),它使用mach_absolute_time(),但会将其转换为CFTimeInterval(即以秒为单位的时间,为双倍)。

答案 2 :(得分:8)

以下是基于计算方法shown heremach_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, running frame rate counts (in milliseconds (*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 HARDWARE SAMPLINGS:
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的危险!

答案 3 :(得分:5)

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