代码之家  ›  专栏  ›  技术社区  ›  zpasternack

iPhone的高分辨率定时器?

  •  13
  • zpasternack  · 技术社区  · 14 年前

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

    HighResolutionTimer* myTimer = [[HighResolutionTimer alloc]init];
    [myTimer start];
    [self doSomeLengthyOperation];
    NSLog( @"doSomeLengthyOperation took %f seconds", [myTimer elapsedTime] );
    
    4 回复  |  直到 14 年前
        1
  •  26
  •   hotpaw2    10 年前

    查看mach/mach\u time.h标题中的mach\u absolute\u time()。

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

        2
  •  16
  •   Pang Ajmal PraveeN    7 年前

    CACurrentMediaTime() mach_absolute_time() CFTimeInterval (即,以秒为单位的时间是一个双精度)为您。

        3
  •  8
  •   bobobobo    11 年前

    这是我的答案时钟计时器使用这两个 mach_absolute_time() shown here ,和 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
    }
    

    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 !

        4
  •  5
  •   lucius    14 年前

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