new*_*mer 37 iphone timer objective-c nsdate nstimer
我正试图用NSTimer制作秒表.
我给出了以下代码:
nst_Timer = [NSTimer scheduledTimerWithTimeInterval:0.001 target:self selector:@selector(showTime) userInfo:nil repeats:NO];
Run Code Online (Sandbox Code Playgroud)
并且它在几毫秒内无法工作.它需要超过1毫秒.
Bro*_*olf 88
不要那样用NSTimer
.NSTimer通常用于在某个时间间隔触发选择器.它的精度不高,不适合你想做的事情.
你想要的是高分辨率计时器类(使用NSDate
):
输出:
Total time was: 0.002027 milliseconds
Total time was: 0.000002 seconds
Total time was: 0.000000 minutes
Run Code Online (Sandbox Code Playgroud)
主要:
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]);
Run Code Online (Sandbox Code Playgroud)
编辑:为-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
Run Code Online (Sandbox Code Playgroud)
Timer.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
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
36933 次 |
最近记录: |