问题
Hi: In an iPhone application I use a library(C++) which asynchronously makes a callback when computation is finished. Now I want to measure the time which is spent -including the method which calls the library- until the callback is made. Are there any possibilities to do this with the Instruments application from Apple? What are the best practices?
回答1:
In the past I have used the following for making network calls I had to optimize - although at first it seems a bit convoluted, it certainly gives the most accurate times I have seen.
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);
}
回答2:
I have written a c++ class to wrap the mach_absolute_time calls. This makes it handy to sprinkle in the code at the start/stop of events for measuring time difference.
It also works well if you want to use it in a class to do timing (between calls) or for state based behavior (do something after the timer reaches X).
StopWatch.h
class StopWatch
{
private:
uint64 _start;
uint64 _stop;
uint64 _elapsed;
public:
void Start();
void Stop();
void Reset();
void Continue();
double GetSeconds();
};
StopWatch.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;
}
来源:https://stackoverflow.com/questions/2673966/measure-time-between-library-call-and-callback