Milliseconds in iPhone applications

Question: I’ve to create a stopwatch for my iPhone app. Is there a way to get a time very precisely? I need to calculate some delays between method calls. I read that I should use NSTimeInterval for this, as well as NSDate, and NSTimer, but I cannot achieve millisecond accuracy with these objects. Can it be done in an iPhone application? I use XCode 3.1. Answer: Your question is about how we use NSTimeInterval. First of all let’s read the NSDate API at Apple: iPhone Dev Center. You must use timeIntervalSinceReferenceDate method that returns NSTimeInterval, the number of “seconds” since the 1980:
// Available in Mac OS X v10.0 and later.
// Declared In NSDate.h

// NSTimeInterval is always specified in seconds
// It yields sub-millisecond
// precision over a range of 10,000 years.

typedef double NSTimeInterval;
As we can see timeIntervalSinceReferenceDate returns double that has microsecond accuracy. So if you are after the millisecond value just multiply by 1000 this value and discard the decimals. Look at this code:
       // Start timer
    NSTimeInterval startTime = [NSDate timeIntervalSinceReferenceDate];
   
      // Do something
    for(double i=0; i < 1000000; i++ );
   
       // Stop timer
    NSTimeInterval endTime = [NSDate timeIntervalSinceReferenceDate];
   
       // Get the elapsed time in milliseconds
    NSTimeInterval elapsedTime = (endTime - startTime) * 1000;

       // Send it to the Console
    NSLog(@"Elapsed time in ms: %f", elapsedTime);
Have fun with it!