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

前端 未结 2 708
醉梦人生
醉梦人生 2021-01-31 04:28

Is is any difference between using mach_absolute_time and the simple NSDate method explained by golden eagle below?

Here\'s an excellen

2条回答
  •  别跟我提以往
    2021-01-31 05:25

    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
    

提交回复
热议问题