下面是一段无法查证出处的英文和自己的翻译
A quick and easy way to measure the performance of a piece of iOS code is to dig down below all the Cocoa Touch stuff and use the low-level mach_absolute_time
. This call returns a tick count that can be converted into nanoseconds using information obtained from themach_timebase_info
call. The following code sketches out the technique:
精确衡量一段ios代码执行效率一个简易快速的方法就是深入挖掘cocoa touch层下面的层次——采用底层调用mach_absolute_time。mach_absolute_time会返回CPU的tick count计数器(私下认为这是cpu的时间),返回的时间可以被转换成毫微秒级。下面附上底层调用mach_absolute_time的实现示范。
add (附上)
#import <mach/mach_time.h>//导入要调用的底层框架
double MachTimeToSecs(uint64_t time) //cpu tickcount 转换成时间的函数
{
mach_timebase_info_data_t timebase;
mach_timebase_info(&timebase);
return (double)time * (double)timebase.numer /
(double)timebase.denom /1e9;
}
- (void)profileDoSomething //检测代码执行时间的方法
{
uint64_t begin = mach_absolute_time(); //用mach_absolute_time()获得时间
//下面是要测试的ios代码,
for (int i = 0; i <1000; i++) {
NSLog(@"test");
}
uint64_t end = mach_absolute_time(); //用mach_absolute_time()获得时间
NSLog(@"Time taken to doSomething %g s",
MachTimeToSecs(end - begin)); //end-begin然后转换,就得到精确的执行时间
}
The timebase values on the simulator, at least on my MacBook Air, are 1/1, however on the iPad and iPhone 4 they are 125/3; so don’t be lazy and hard code them.
(此段英文主要讲不同的测试设备得到的结果不同,由于楼主不晓得1/1,125/3什么意思所以这段就不翻译了)
Never assume that because something runs quickly on the simulator it will also run quickly on a target device. On two jobs last year I encountered code that took 100x longer to run an iPad than in the simulator.
永远不要假设代码在模拟器上的执行效率和在目标设备(比如iPhone 5)上的执行效率一样。我去年遇见过一段代码在iPad上比在模拟器上多跑了100X。