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);

 

posted @ 2014-10-24 13:25  菜鸟程序猿  阅读(1488)  评论(0编辑  收藏  举报