PDA

View Full Version : Help to time a loop




mdeh
Feb 22, 2009, 10:10 AM
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

#import <Foundation/NSDate.h>


@interface NSDate (DateOps)

+(id)dateNow;

+(NSTimeInterval) timeSince: (NSDate*) startOfLoop;

@end

Time.m
#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)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.



kainjow
Feb 22, 2009, 11:01 AM
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.

lee1210
Feb 22, 2009, 11:35 AM
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

mdeh
Feb 22, 2009, 01:12 PM
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.

Thank you.

mdeh
Feb 22, 2009, 01:12 PM
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

Thank you for pointing that out.