Created
March 7, 2014 22:40
-
-
Save kristopherjohnson/9421694 to your computer and use it in GitHub Desktop.
Measures elapsed time in Cocoa app
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import <Foundation/Foundation.h> | |
// Calculates the time elapsed since it was created, | |
// or since the last time it was reset. | |
@interface KDJStopwatch : NSObject | |
// Reset the start time to the current time | |
- (void)reset; | |
// Return number of seconds elapsed between initialization (or the last call to -reset) and now | |
- (NSTimeInterval)elapsedTimeInterval; | |
// Return user-readable string for elapsed time | |
- (NSString *)elapsedTimeString; | |
@end |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#import "KDJStopwatch.h" | |
#import <QuartzCore/QuartzCore.h> | |
@implementation KDJStopwatch { | |
NSTimeInterval _startTime; | |
} | |
- (id)init { | |
self = [super init]; | |
if (self) { | |
[self reset]; | |
} | |
return self; | |
} | |
- (void)reset { | |
_startTime = CACurrentMediaTime(); | |
} | |
- (NSTimeInterval)elapsedTimeInterval { | |
return CACurrentMediaTime() - _startTime; | |
} | |
- (NSString *)elapsedTimeString { | |
double interval = [self elapsedTimeInterval]; | |
if (interval < 1) { | |
return [NSString stringWithFormat:NSLocalizedString(@"%.1f ms", @"KDJStopwatch elapsedTimeFormat ms"), interval * 1000]; | |
} | |
else { | |
return [NSString stringWithFormat:NSLocalizedString(@"%.2f s", @"KDJStopwatch elapsedTimeFormat sec"), interval]; | |
} | |
} | |
- (NSString *)description { | |
return [NSString stringWithFormat:@"<KDJStopwatch: %p; elapsed: %g>", | |
self, (double)self.elapsedTimeInterval]; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Example usage: