2

嗨:在 iPhone 应用程序中,我使用了一个库(C++),它在计算完成时异步进行回调。现在我想测量花费的时间 - 包括调用库的方法 - 直到进行回调。是否有可能使用 Apple 的 Instruments 应用程序来做到这一点?最佳实践是什么?

4

2 回答 2

8

过去,我使用以下方法进行网络调用,我必须优化 - 虽然起初看起来有点复杂,但它确实给出了我见过的最准确的时间。

uint64_t time_a = mach_absolute_time();

// do stuff

uint64_t time_b = mach_absolute_time();

[self logTime:(time_b-time_a)];

- (void) logTime:(uint64_t)machTime {
    static double timeScaleSeconds = 0.0;
    if (timeScaleSeconds == 0.0) {
        mach_timebase_info_data_t timebaseInfo;
        if (mach_timebase_info(&timebaseInfo) == KERN_SUCCESS) {
            double timeScaleMicroSeconds = ((double) timebaseInfo.numer / (double) timebaseInfo.denom) / 1000;
            timeScaleSeconds = timeScaleMicroSeconds / 1000000;
        }
    }

    NSLog(@"%g seconds", timeScaleSeconds*machTime);
}
于 2010-04-20T21:42:40.810 回答
0

我编写了一个 c++ 类来包装 mach_absolute_time 调用。这使得在事件的开始/停止时撒上代码来测量时差变得很方便。

如果您想在类中使用它来进行计时(在调用之间)或用于基于状态的行为(在计时器到达 X 后做某事),它也很有效。

秒表.h

class StopWatch
{
private:
        uint64 _start;
        uint64 _stop;
        uint64 _elapsed;
public:
   void Start();
   void Stop();
   void Reset();
   void Continue();
   double GetSeconds();
};

秒表.cpp

#include "Stopwatch.h"
#include <mach/mach_time.h>


void StopWatch::Start()
{
        _stop = 0;
        _elapsed = 0;
        _start = mach_absolute_time();
}

void StopWatch::Stop()
{
        _stop = mach_absolute_time();
   if(_start > 0)
   {
      if(_stop > _start)
      {
         _elapsed = _stop - _start;
      }
   }
}

void StopWatch::Reset()
{
   _start = 0;
   _stop  = 0;
   _elapsed = 0;
}

void StopWatch::Continue()
{
   _elapsed = 0;
   _stop = 0;
}

double StopWatch::GetSeconds()
{
   double elapsedSeconds = 0.0;
   uint64 elapsedTimeNano = 0;

        if(_elapsed > 0)
        {  // Stopped
                mach_timebase_info_data_t timeBaseInfo;
                mach_timebase_info(&timeBaseInfo);
                elapsedTimeNano = _elapsed * timeBaseInfo.numer / timeBaseInfo.denom;
                elapsedSeconds = elapsedTimeNano * 1.0E-9;
        }
        else if(_start > 0)
        {  // Running or Continued
      uint64_t elapsedTemp;
                uint64_t stopTemp = mach_absolute_time();
      if(stopTemp > _start)
      {
         elapsedTemp = stopTemp - _start;
      }
      else
      {
         elapsedTemp = 0;
      }
                mach_timebase_info_data_t timeBaseInfo;
                mach_timebase_info(&timeBaseInfo);
                elapsedTimeNano = elapsedTemp * timeBaseInfo.numer / timeBaseInfo.denom;
                elapsedSeconds = elapsedTimeNano * 1.0E-9;
        }
   return elapsedSeconds;
}
于 2014-01-02T13:51:09.007 回答