0

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

- (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

定时器.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
4

1 回答 1

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
于 2013-02-03T00:56:57.397 回答