Help to time a loop

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

  1. macrumors 6502

    Joined:
    Jan 3, 2009
    #1
    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.
    Time.h

    Code:
    #import <Foundation/NSDate.h>
    
    
    @interface NSDate (DateOps)
    
    +(id)dateNow; 
    
    +(NSTimeInterval) timeSince: (NSDate*) startOfLoop; 
    
    @end
    Time.m
    Code:
    #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 */
    }
    
    
    @end
    main.m (example of use)
    Code:
    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. Moderator emeritus

    kainjow

    Joined:
    Jun 15, 2000
    #2
    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. macrumors 68040

    lee1210

    Joined:
    Jan 10, 2005
    Location:
    Dallas, TX
    #3
    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.

    -Lee
     
  4. thread starter macrumors 6502

    Joined:
    Jan 3, 2009
    #4
    Thank you.
     
  5. thread starter macrumors 6502

    Joined:
    Jan 3, 2009
    #5
    Thank you for pointing that out.
     

Share This Page