Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rudimentary ways to measure execution time of a method

Tags:

objective-c

What object/method would I call to get current time in milliseconds (or great precision) to help measure how long a method took to execute?

NSDate's timeIntervalSinceDate will return NSInterval which is measured in seconds. I am looking for something finer grained, something similar to Java's System.currentTimeMillis.

Is there an equivalent version in objective-c/CocoaTouch?

like image 787
Alexi Groove Avatar asked Oct 23 '09 21:10

Alexi Groove


People also ask

How do we measure the execution time of programs?

The difference between the end time and start time is the execution time. Get the execution time by subtracting the start time from the end time.

How is execution measured?

The easiest way to track execution time is to use a date object. Using Date. now() that returns the total number of milliseconds elapsed since the Unix epoch, we can store the value before and after the execution of the function to be measured and then get the difference of the two.

How is execution speed calculated?

Measure execution time to the nearest 10 msec. Then divide that time bythe number of times the loop executed. If the loop executed 1000 timesusing a 10 msec clock, you obtain a resolution of 10 µsec for theloop.

What is execution time of a program?

Execution time refers to the stage at which the instructions in the computer programs/code are executed. At execution time, run-time libraries are used. Some basic operations that occur at execution time include reading program instructions to carry out tasks or complete actions.


1 Answers

For very fine-grained timings on OS X, I use mach_absolute_time( ), which is defined in <mach/mach_time.h>. You can use it as follows:

#include <mach/mach_time.h>
#include <stdint.h>

static double ticksToNanoseconds = 0.0;

uint64_t startTime = mach_absolute_time( );
// Do some stuff you want to time here
uint64_t endTime = mach_absolute_time( );

 // Elapsed time in mach time units
uint64_t elapsedTime = endTime - startTime;

// The first time we get here, ask the system
// how to convert mach time units to nanoseconds
if (0.0 == ticksToNanoseconds) {
    mach_timebase_info_data_t timebase;
    // to be completely pedantic, check the return code of this next call.
    mach_timebase_info(&timebase);
    ticksToNanoseconds = (double)timebase.numer / timebase.denom;
}

double elapsedTimeInNanoseconds = elapsedTime * ticksToNanoseconds;
like image 63
Stephen Canon Avatar answered Nov 15 '22 07:11

Stephen Canon