首页 > 代码库 > Objective-C 计算代码运行时间

Objective-C 计算代码运行时间

转自:http://www.isaced.com/post-213.html

 

Objective-C 计算代码运行时间

今天看到一篇关于iOS应用性能优化的文章,其中提到计算代码的运行时间,觉得非常有用,值得收藏。不过在模拟器和真机上是有差异的,以此方法观察程序运行状态,提高效率。

第一种:(最简单的NSDate

NSDate* tmpStartData = http://www.mamicode.com/[NSDate date];"cost time = %f", deltaTime);

#import <mach/mach_time.h>  // for mach_absolute_time() and friends    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;  }

/** * 计算脚本时间 * @param $last	最后一次的运行clock * @param $key	标识 * @return 当前clock */double t(double last, char* key){    clock_t now = clock();    printf("time:%fs \t key:%s \n", (last != 0) ? (double)(now - last) / CLOCKS_PER_SEC : 0, key);    return now;}double t1 = t(0, "");//do somethingt(t1, "end");

 


飘飘白云文中说到,对于UIImage载入图像的方法,下面第一种更为高效,因为iOS会自带 cache 载入图像。

+ (UIImage *)imageNamed:(NSString *)name;- (id)initWithContentsOfFile:(NSString *)path;

正好这里总结到计算代码运行时间,就以此为例看看两种方法到底谁更高效,这里我用最简单的NSDate计算耗时:

    for (int i=0 ; i<10000; i++) {        UIImage *image = [UIImage imageNamed:@"icon.png"];//        UIImage *image = [[UIImage alloc] initWithContentsOfFile:@"icon.png"];        image = nil;    }    double deltaTime = [[NSDate date] timeIntervalSinceDate:tmpStartData];    NSLog(@"cost time = %f", deltaTime);

cost time = 0.022821 //imageNamedcost time = 0.102620 //initWithContentsOfFile

Objective-C 计算代码运行时间