mac获取方法的执行时间

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;

}

 

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

调用方法如下

 

Oc代码    收藏代码
  1. int main (void) {    
  2.     CGFloat time;    
  3.     
  4.     NSString *thing1 = @"hi";    
  5.     NSString *thing2 = @"hello there";    
  6.     
  7.     time = BNRTimeBlock(^{    
  8.             for (int i = 0; i < LOOPAGE; i++) {    
  9.                 [thing1 isEqual: thing2];    
  10.             }    
  11.         });    
  12.     printf ("isEqual: time: %f\n", time);    
  13.     
  14.     time = BNRTimeBlock(^{    
  15.             for (int i = 0; i < LOOPAGE; i++) {    
  16.                 [thing1 isEqualToString: thing2];    
  17.             }    
  18.         });    
  19.     printf ("isEqualToString: time: %f\n", time);    
  20.     
  21.     return 0;    

引入包

#import <mach/mach_time.h>

例如:
#import <mach/mach_time.h>

uint64_t start = mach_absolute_time();

// do stuff to be timed

uint64_t end = mach_absolute_time();
uint64_t elapsed = end - start;

mach_timebase_info_data_t info;
if (mach_timebase_info (&info) != KERN_SUCCESS) {
printf ("mach_timebase_info failed\n");
}

uint64_t nanosecs = elapsed * info.numer / info.denom;
uint64_t millisecs = nanosecs / 1000000;

你可能感兴趣的:(mac)