iOS设备相对于电脑,内存和处理能力有限,所以一段代码或者程序运行的时间需要时刻注意,这里提供两种获取精确时间的方法。
方法一:使用系统时间
1 NSDate* tmpStartData = [[NSDate date] retain]; 2 //You code here... 3 double deltaTime = [[NSDate date] timeIntervalSinceDate:tmpStartData]; 4 NSLog(@">>>>>>>>>>cost time = %f ms", deltaTime*1000);
方法二:
1 #import <mach/mach_time.h> 2 3 uint64_t start = mach_absolute_time(); 4 //You code here... 5 uint64_t end = mach_absolute_time(); 6 uint64_t elapsed = end - start;mach_timebase_info_data_t info; 7 if (mach_timebase_info (&info) != KERN_SUCCESS) 8 { 9 printf ("mach_timebase_info failed\n"); 10 } 11 uint64_t nanosecs = elapsed * info.numer / info.denom; 12 uint64_t millisecs = nanosecs / 1000000; 13 NSLog(@">>>>>>>>>>cost time = %ld ms", millisecs);
时间: 2024-10-15 08:43:08