iOS获取一个方法的执行时间

#import <Foundation/Foundation.h>
#import <mach/mach_time.h>

typedef void (^block)(void);

@interface FunctionRunTime : NSObject

+ (CGFloat)runTimeBlock:(block)block;

@end


#import "FunctionRunTime.h"

@implementation FunctionRunTime

+ (CGFloat)runTimeBlock:(block)block
{
    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;
    
} // BNRTimeBlock

@end

// 使用
CGFloat time= [FunctionRunTime runTimeBlock:^{
        for (int i = 0; i < 1000; i++) {
 }];
NSLog ("time: %f\n", time);

 

郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。