2011-01-23 39 views
23

是否使用mach_absolute_time和簡單的NSDate下面用金鷹解釋的方法有什麼區別?用於測量iPad或手機上的代碼內EXACT執行時間的代碼?

下面是使用馬赫方法的一個很好的解釋...

How do I accurately time how long it takes to call a function on the iPhone?

Measure time between library call and callback

+0

possible [我如何精確計時需要多長時間才能調用iPhone上的函數?](http://stackoverflow.com/questions/646815/how-do-i-accurately-time-how-long-it-需要iphone上的功能) – 2011-01-24 19:46:25

回答

76
loop 
    { 
    NSDate *start = [NSDate date]; 

    // a considerable amount of difficult processing here 
    // a considerable amount of difficult processing here 
    // a considerable amount of difficult processing here 

    NSDate *methodFinish = [NSDate date]; 
    NSTimeInterval executionTime = [methodFinish timeIntervalSinceDate:start]; 

    NSLog(@"Execution Time: %f", executionTime); 
    } 

應該工作。

+0

答案能解決您的問題嗎? – 2011-01-23 12:43:07

+11

好吧,iPhone開發者,大家休息一下。 – Will 2011-01-27 12:15:57

2

在以前answear我實現了一個簡單的類來計算時間

工作原理:

ABTimeCounter *timer = [ABTimeCounter new]; 
[timer restart]; 

//do some calculations 

[timer pause]; 

//do some other staff 

[timer resume]; 

//other code 

//You can measure current time immediately 

NSLog(@"Time left from starting calculations: %f seconds",[timer measuredTime]); 

[timer pause]; 

您的.h文件中應該是這樣的:

@interface ABTimeCounter : NSObject 
@property (nonatomic, readonly) NSTimeInterval measuredTime; 

- (void)restart; 
- (void)pause; 
- (void)resume; 

@end 

.m文件:

@interface ABTimeCounter() 
@property (nonatomic, strong) NSDate *lastStartDate; 
@property (nonatomic) BOOL isCounting; 
@property (nonatomic, readwrite) NSTimeInterval accumulatedTime; 
@end 

@implementation ABTimeMeasure 

#pragma mark properties overload 

- (NSTimeInterval) measuredTime 
{ 
    return self.accumulatedTime + [self p_timeSinceLastStart]; 
} 

#pragma mark - public - 

- (void) restart 
{ 
    self.accumulatedTime = 0; 
    self.lastStartDate = [NSDate date]; 
    self.isCounting = YES; 
} 

- (void) pause 
{ 
    if (self.isCounting){ 
     self.accumulatedTime += [self p_timeSinceLastStart]; 
     self.lastStartDate = nil; 
     self.isCounting = NO; 
    } 
} 

- (void) resume 
{ 
    if (!self.isCounting){ 
     self.lastStartDate = [NSDate date]; 
     self.isCounting = YES; 
    } 
} 

#pragma mark - private - 

- (NSTimeInterval) p_timeSinceLastStart 
{ 
    if (self.isCounting){ 
     return [[NSDate date] timeIntervalSinceDate:self.lastStartDate]; 
    } 
    else return 0; 
} 

@end