簡體   English   中英

iPhone的高分辨率計時器?

[英]High-resolution timer for iPhone?

我正在尋找iPhone的高分辨率計時代碼,以執行一些性能計時。 我想寫這樣的代碼:

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

在mach / mach_time.h標頭中查看mach_absolute_time()。

不要使用NSDate。 當ntp執行其操作時,NSDate甚至不保證偶爾不會倒退。

(設備可能會有時鍾漂移。如果iOS設備漂移了幾秒鍾,那么當NTP糾正這種漂移時,您會看到時鍾突然倒退了幾秒鍾。這對計時使用非常不利。mach_time使用的計數器不會永遠不會被NTP糾正,因此不會向后退,因此計時效果會更好。)

更好的選擇是CACurrentMediaTime() ,它使用mach_absolute_time()但會為您將其轉換為CFTimeInterval (即,以秒為單位的時間為兩倍)。

這是我使用基於此處所示的計算方法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, 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

使用NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate]獲取開始時間,然后使用NSLog (@"Operation took %f seconds.", [NSDate timeIntervalSinceReferenceDate] - startTime); 在最后。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM