开发者

Code to measure EXACT execution time inside code on iPad or Phone?

开发者 https://www.devze.com 2023-02-06 19:30 出处:网络
Is 开发者_开发问答is any difference between using mach_absolute_time and the simple NSDate method explained by golden eagle below?

Is 开发者_开发问答is any difference between using mach_absolute_time and the simple NSDate method explained by golden eagle below?

Here's an excellent explanation of using the mach approach...

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

and

Measure time between library call and callback


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

Should work.


Upon previous answear I have implemented a simple class to measure time

How it works:

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];

your .h file should look like this:

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

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

@end

.m file:

@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
0

精彩评论

暂无评论...
验证码 换一张
取 消