获取方法的执行时间

CGFloat BNRTimeBlock (void (^block)(void)) {  
    mach_timebase_info_data_t info;  
    if (mach_timebase_info(&info) != KERN_SUCCESS) return -1.0;  
  
    uint64_t start = mach_absolute_time ();  
    block ();  
    uint64_t end = mach_absolute_time ();  
    uint64_t elapsed = end - start;  
  
    uint64_t nanos = elapsed * info.numer / info.denom;  
    return (CGFloat)nanos / NSEC_PER_SEC;  
  
} 

将目标方法放在块语法中,可得到目标方法的执行时间

调用方法如下

int main (void) {  
    CGFloat time;  
  
    NSString *thing1 = @"hi";  
    NSString *thing2 = @"hello there";  
  
    time = BNRTimeBlock(^{  
            for (int i = 0; i < LOOPAGE; i++) {  
                [thing1 isEqual: thing2];  
            }  
        });  
    printf ("isEqual: time: %f\n", time);  
  
    time = BNRTimeBlock(^{  
            for (int i = 0; i < LOOPAGE; i++) {  
                [thing1 isEqualToString: thing2];  
            }  
        });  
    printf ("isEqualToString: time: %f\n", time);  
  
    return 0;  
} 
 

你可能感兴趣的:(ios,方法,oc,执行时间)