在iPad或手机上测量代码内部的确切执行时间的代码?

23

可能是重复的问题:如何准确计时iPhone上调用函数所需的时间? - Brad Larson
2个回答

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);
  }

应该可以工作。


11
好的,iPhone 开发人员们,请休息一下喝杯咖啡。 - user1228

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

@Maq,您能否提供更多有关您评论的细节? - Nikolay Shubenkov

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接