Transferred from: http://www.isaced.com/post-213.html
OBJECTIVE-C Calculating code run time
June 25
Today I saw an article on the performance optimization of iOS apps, which mentions the running time of the calculation code, which is very useful and worth collecting. However, there is a difference between the simulator and the real machine, in this way to observe the program running state, improve efficiency.
The first type: (The simplest nsdate)
nsdate* tmpstartdata = [nsdate date];//you code here...double deltatime = [[NSDate Date] Timeintervalsincedate:tmpstartda TA]; NSLog (@ "Cost time =%f", deltatime);
The second type: (Put the running code in the block below, return the time)
#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; }
The third type:
/** * Calculate the script time * @param $last last Run clock * @param $key identification * @return Current clock */double t (double last, char* key) { clock_t now = Clock (); printf ("Time:%fs \ key:%s \ n", (last! = 0)? (double) (now-last)/clocks_per_sec:0, key); return now;} Double t1 = t (0, "");//do somethingt (T1, "end");
Floating Baiyun Wen said, for the UIImage load image method, the following first is more efficient, because iOS will bring the cache loaded image.
+ (UIImage *) imagenamed: (NSString *) name;-(ID) initwithcontentsoffile: (NSString *) path;
However, the Imagenamed method can only load files in bundles, such as network image parsing.
Just to summarize here to calculate the code run time, take this as an example to see which of the two methods is more efficient, here I use the simplest nsdate calculation time:
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);
Output Result:
Cost time = 0.022821//imagenamedcost time = 0.102620//initwithcontentsoffile
Here picture I use a 1024x1024 pixel png, can be seen two ways to load the image time difference is quite large.
OBJECTIVE-C Calculating code run time