Help to time a loop

Discussion in 'Mac Programming' started by mdeh, Feb 22, 2009.

  1. mdeh macrumors 6502

    Jan 3, 2009
    Hi all,
    I want to set up a little program to time a loop.
    This is what I have come up with...your input/criticism would be most helpful.

    #import <Foundation/NSDate.h>
    @interface NSDate (DateOps)
    +(NSTimeInterval) timeSince: (NSDate*) startOfLoop; 
    #import "Time.h"
    @implementation NSDate (DateOps)
    +(id) dateNow
    	NSDate *today = [NSDate date];
    	return today;
    +(NSTimeInterval) timeSince: (NSDate*) startOfLoop;
    	return -( 1000 * [ startOfLoop timeIntervalSinceNow]); /* returns milli-seconds */
    main.m (example of use)
    int main (int argc, const char * argv[]) {
        NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
    	NSAutoreleasePool *tempPool;
    	int x;
    	NSDate *startOfLoop = [ NSDate dateNow];
    	for ( x = 0; x < 100000; x ++)
    	tempPool = [ [ NSAutoreleasePool alloc] init]; 
    	NSString *myS = [[NSString alloc]initWithString: @"test"];
    	if ( x % 10 )
    	[myS autorelease];   
    	[tempPool drain]; 
    	NSTimeInterval elapsedTime = [NSDate timeSince:startOfLoop];
    	NSLog(@"Elapsed Time: %g milliseconds", elapsedTime);
        [pool drain];
        return 0;
    To me the timeSince: method feels really awkward...but that's what seems to work. Thanks for your help.
  2. kainjow Moderator emeritus


    Jun 15, 2000
    Your dateNow method is doing nothing special, just use [NSDate date], and your other method can be replaced with timeIntervalSinceDate:

    Or just use CFAbsoluteTimeGetCurrent() which is more direct.
  3. lee1210 macrumors 68040


    Jan 10, 2005
    Dallas, TX
    Not related to the the time items, but you're leaking in your loop. You only send autorelease to 9 out of every 10 strings you allocate in the loop. Pull the autorelease outside of the if(x %10), and change that if to if((x % 10) == 0). Right now 9 out of every 10 iterations you are sending autorelease, and draining the pool. The 10th time, you don't send autorelease, so the retain count of the NSString is still 1, and you do not drain the pool.

  4. mdeh thread starter macrumors 6502

    Jan 3, 2009
    Thank you.
  5. mdeh thread starter macrumors 6502

    Jan 3, 2009
    Thank you for pointing that out.

Share This Page