views:

414

answers:

2

I have a little project that is a timer that counts down 'til midnight, and I was wondering If I should leave it as it is, calculating the time until midnight each second (inside NSTimer method that gets called every 1 second):

NSDate *now = [[NSDate alloc] init];
NSDateComponents *dateComponents = [[self gregorian] components:
     (NSHourCalendarUnit |
     NSMinuteCalendarUnit |
     NSSecondCalendarUnit) fromDate:now];
[now release];
NSUInteger hour = 23 - [dateComponents hour];
NSUInteger min = 59 - [dateComponents minute];
NSUInteger sec = 59 - [dateComponents second];

NSString *time = [[NSString alloc] initWithFormat:@"%02d:%02d:%02d",
      hour, min, sec];
[[self lblCountDown] setText:
 [time stringByReplacingOccurrencesOfString:@"1" withString:@" 1"]];
[time release];

or should I just calculate that the first time, and then every other time just subtract one second each time since its synced to 1 second per call? I'm not worried that this will take longer than 1 second, but if the result will be the same the other way there's no reason not to optimize.. so anyway, should I do it that way? And why?

Thanks.

+1  A: 

The statement "there's no reason not to optimize" is a dangerous one. You need a reason to optimize, not a lack of a reason not to! That code is a fairly reasonable little snip that won't take much time to execute.

As for accuracy, the only reasonable way to keep accurate time is to let the system do it for you, getting the "now" time is a way of doing that. Taking it into your own hands will likely lead to the clock drifting into error, maybe enough to notice, maybe not.

As for the optimization, profile it, see how fast it is, if it sucks, fix it, if it doesn't, move on to something more fun!

Nick Veys
I put both ways and made it log if they were the same, and its been going for a while, always true.
Mk12
Seems reasonable. You might see drift on a microcontroller or something, but not on a speedy device like this.
Nick Veys
+1  A: 

Premature optimization is always BAD, do not write code today that you can not debug a year later. Never do any optimization until you:

  1. Have a working application.
  2. The working application have actual bad performance.
  3. You have done instrumentation to find the actual bootle-neck.
  4. You are sure you are using the best algorithm.
  5. Figured out how to optimize without sacrificing code clarity.

With that all said and done, checking for the current time once every second can never degenerate your performance. So obviously you have not even passed requirement 2 for applying optimizations.

PeyloW