目标C,在NSLog中获得nan

时间:2013-02-02 19:57:43

标签: objective-c nsdate nan

我想在2点之间获得时间。我不知道我做错了什么,但我的NSLog给了我“nan”的结果。总时间为:秒。如果我从if语句中删除[timer start]和[timer stop],那么它会给出正常的double结果。

- (void) filterFrequency {

Timer *timer = [[Timer alloc] init];
if (self.currentFrequency > 2000 && pointInTime % 2 == 0)

{
    [timer startTimer];
    pointInTime = pointInTime + 1;
}
 else if (self.currentFrequency > 2000 && pointInTime % 2 == 1)

{
    [timer stopTimer];
    pointInTime = pointInTime + 1;
    NSLog(@"Total time was: %f seconds", [timer timeElapsedInSeconds]);

}

这是Timer.h     #import

@interface Timer : NSObject {
NSDate *start;
NSDate *end;
}

- (void) startTimer;
- (void) stopTimer;
- (double) timeElapsedInSeconds;
- (double) timeElapsedInMilliseconds;
- (double) timeElapsedInMinutes;

@end

Timer.m

#import "Timer.h"
#import "ListenerViewController.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

1 个答案:

答案 0 :(得分:0)

我使用以下代码来衡量声音需要加载的时间。我不知道你想在你的代码中做什么(以及为什么),但这个对于精确的时间测量肯定是有用的。

    // Setup:

    uint64_t tm_start,tm_end,tm_elapsed,tm_nanoSeconds,tm_milliSeconds,tm_seconds;
    mach_timebase_info_data_t info;

    // Start:
    tm_start = mach_absolute_time();    

    // do your stuff 

    // Example
    NSSound *cocoaAudioPlayerSound = [[NSSound alloc] initWithContentsOfFile:mediaLocation byReference:YES];
    // … time flies


    // End:
    tm_end = mach_absolute_time();
    tm_elapsed = tm_end - tm_start;
    mach_timebase_info(&info); 
    tm_nanoSeconds = tm_elapsed * info.numer / info.denom;
    tm_milliSeconds = tm_nanoSeconds / (1000000);
    tm_seconds = (tm_milliSeconds/1000);

#ifdef DEBUG
    fflush(stdout);
    printf ( "| allocateAudio: %5lld milliseconds (%5lld seconds) (%12lld nano seconds)\n", tm_milliSeconds, tm_seconds, tm_nanoSeconds );
#endif