Objective-C超高精度的计时器

今天引用在stackoverflow上看到的一个网友给出的解决方案:使用NSDate构建一个高精度计时器

输出如下:

Total time was: 0.002027 milliseconds
Total time was: 0.000002 seconds
Total time was: 0.000000 minutes

调用程序:

Timer *timer = [[Timer alloc] init];
[timer startTimer];
// Do some work
[timer stopTimer];
NSLog(@"Total time was: %lf milliseconds", [timer timeElapsedInMilliseconds]);
NSLog(@"Total time was: %lf seconds", [timer timeElapsedInSeconds]);
NSLog(@"Total time was: %lf minutes", [timer timeElapsedInMinutes]);

编辑类:加入-timeElapsedInMilliseconds(计算毫秒)与 -timeElapsedInMinutes(计算分钟)两个方法

Timer.h

#import <Foundation/Foundation.h>
@interface Timer : NSObject {
NSDate *start;
NSDate *end;
}
- (void) startTimer;
- (void) stopTimer;
- (double) timeElapsedInSeconds;
- (double) timeElapsedInMilliseconds;
- (double) timeElapsedInMinutes;
@end

Time.m

#import "Timer.h"
@implementation Timer
- (id) init {
self = [super init];
if (self != nil) {
start = nil;
end = nil;
}
return self;
}
- (void) startTimer {
start = [NSDate date];
}
- (void) stopTimer {
end = [NSDate date];
}
- (double) timeElapsedInSeconds {
return [end timeIntervalSinceDate:start];
}
- (double) timeElapsedInMilliseconds {
return [self timeElapsedInSeconds] * 1000.0f;
}
- (double) timeElapsedInMinutes {
return [self timeElapsedInSeconds] / 60.0f;
}
@end