I would like to know how long it's taking to send a message to an object with at least a 1ms accuracy. How do I do this?
问题:
回答1:
You can use mach_absolute_time
to measure in nanoseconds.
#import <mach/mach_time.h>
uint64_t startTime = 0;
uint64_t endTime = 0;
uint64_t elapsedTime = 0;
uint64_t elapsedTimeNano = 0;
mach_timebase_info_data_t timeBaseInfo;
mach_timebase_info(&timeBaseInfo);
startTime = mach_absolute_time();
//do something here
endTime = mach_absolute_time();
elapsedTime = endTime - startTime;
elapsedTimeNano = elapsedTime * timeBaseInfo.numer / timeBaseInfo.denom;
Reference: Technical Q&A QA1398: Mach Absolute Time Units
回答2:
Here's what I do:
NSDate * start = [NSDate date];
// do whatever I need to time
NSLog(@"time took: %f", -[start timeIntervalSinceNow]);
The output will be in seconds (with a decimal portion). NSDate
s have resolution on the scale of milliseconds, although I'm not sure precisely how accurate they are.
If the code you're trying to time is too fast, put it in a loop that runs the code a hundred times. (That assumes, of course, that the code you're timing has no side effects.)
回答3:
Use dispatch_benchmark to log method execution time in nanoseconds.
It has a much nicer syntax than manually looping and calling mach_absolute_time() dispatch_benchmark is part of Grand Central Dispatch. This function is not publicly declared, so you’ll have to do that yourself before use :
extern uint64_t dispatch_benchmark(size_t count, void (^block)(void));
I am using this for log execution time :
size_t const blockIterations = 1; //block call count
uint64_t t = dispatch_benchmark(blockIterations, ^{ //your code inside block
[self TEST_processJSONDataRecordsWithCompletionHandler:^(id handler) {}];
});
NSLog(@" Avg. Runtime in nanoseconds : %llu ns", t);
Credit goes to Benchmarking