用于衡量iPad或手机代码内的完整执行时间的代码?

时间:2011-01-23 11:56:33

标签: iphone xcode ipad ios

使用 mach_absolute_time 与下面的金鹰解释的简单 NSDate 方法有什么区别?

这是使用马赫方法的一个很好的解释......

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

Measure time between library call and callback

2 个答案:

答案 0 :(得分: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);
  }

应该有效。

答案 1 :(得分:2)

以前的衣着我实施了一个简单的课程来衡量时间

工作原理:

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