Skip to content

Instantly share code, notes, and snippets.

@kristopherjohnson
Created March 7, 2014 22:40
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kristopherjohnson/9421694 to your computer and use it in GitHub Desktop.
Save kristopherjohnson/9421694 to your computer and use it in GitHub Desktop.
Measures elapsed time in Cocoa app
#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
#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
@kristopherjohnson
Copy link
Author

Example usage:

KDJStopwatch *stopwatch = [[KDJStopwatch alloc] init];

// Do some time-consuming operation
// ...

NSLog("elapsed time: %@", [stopwatch elapsedTimeString]);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment