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;
- }
引入包
#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;