Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I accurately time how long it takes to call a function on the iPhone?

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?

like image 330
Tommy Avatar asked Mar 14 '09 21:03

Tommy


2 Answers

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

like image 83
digdog Avatar answered Nov 14 '22 17:11

digdog


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). NSDates 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.)

like image 11
Becca Royal-Gordon Avatar answered Nov 14 '22 19:11

Becca Royal-Gordon