Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I measure the time it takes between two lines of code in Objective-C for iOS?

I have the following code that is taking a while to process:

self.itemsArray = [Helper changeTheA:self.itemsArray];
self.itemsArray = [Helper convertDates:self.itemsArray];

Is there a way, in Instruments or somewhere else, that I can measure the time is takes to go from the first line of code to the second line of code.... in ticks or milliseconds or something?

I want to do some tweaking but I need to be able to measure in order to see if I'm making an improvement over the previous code.

like image 238
Ethan Allen Avatar asked Apr 18 '12 23:04

Ethan Allen


3 Answers

Quickest, dirtiest, possibly not very precise way

NSDate *startDate = [NSDate date];

self.itemsArray = [Helper changeTheA:self.itemsArray];

NSLog(@"changeTheA time taken: %f", -[startDate timeIntervalSinceNow]);

A slightly more involved but probably more useful solution, if you are doing some basic profiling can be seen here, it uses a C function that executes a block you provide.


Big side note

As Justin points out the actual act of creating an NSDate and then logging it out will introduce interference to your measurements and so this technique is only really any good for getting ball park figures and even then you should probably run large amounts of iterations of your code within the timing block. If you require accurate measurements then skip to Justin's answer

like image 56
Paul.s Avatar answered Nov 02 '22 05:11

Paul.s


Yes. You would use Instruments' Sampler for this.

Run the app, exercise the program for a while, then locate the symbol in Instruments which contains:

self.itemsArray = [Helper changeTheA:self.itemsArray];
self.itemsArray = [Helper convertDates:self.itemsArray];

It should show the weights line by line. Also note that Instruments allows you to specify the sampling frequency, down to 40 microseconds.

like image 32
justin Avatar answered Nov 02 '22 04:11

justin


I would use the following code:

NSTimeInterval start = CACurrentMediaTime();

// your code goes here

NSTimeInterval end = CACurrentMediaTime();
NSTimeInterval delta = end - start;
NSLog(@"Execution took %f seconds.", delta);

It is a lot more precise than NSDate.

like image 20
Christian Schnorr Avatar answered Nov 02 '22 04:11

Christian Schnorr