以main()函数作为分界点,main()函数之前部分叫做pre-main。
pre-main
我们可以在 Xcode 中配置环境变量 DYLD_PRINT_STATISTICS 为 1(Edit Scheme → Run → Arguments → Environment Variables → +)。
这时在 iOS 10 以上系统中运行一个 TestDemo,main()函数之前的启动时间会在控制台中打印出来。
Total pre-main time: 354.21 milliseconds (100.0%)
dylib loading time: 25.52 milliseconds (7.2%)
rebase/binding time: 12.70 milliseconds (3.5%)
ObjC setup time: 152.74 milliseconds (43.1%)
initializer time: 163.24 milliseconds (46.0%)
slowest intializers :
libSystem.B.dylib : 7.98 milliseconds (2.2%)
libBacktraceRecording.dylib : 13.53 milliseconds (3.8%)
libMainThreadChecker.dylib : 41.11 milliseconds (11.6%)
TestDemo : 88.76 milliseconds (25.0%)
如果要更详细的信息,就设置 DYLD_PRINT_STATISTICS_DETAILS 为 1。
total time: 1.6 seconds (100.0%)
total images loaded: 388 (381 from dyld shared cache)
total segments mapped: 23, into 413 pages
total images loading time: 805.78 milliseconds (48.6%)
total load time in ObjC: 152.74 milliseconds (9.2%)
total debugger pause time: 780.26 milliseconds (47.1%)
total dtrace DOF registration time: 0.00 milliseconds (0.0%)
total rebase fixups: 54,265
total rebase fixups time: 20.77 milliseconds (1.2%)
total binding fixups: 527,211
total binding fixups time: 513.54 milliseconds (31.0%)
total weak binding fixups time: 0.31 milliseconds (0.0%)
total redo shared cached bindings time: 521.93 milliseconds (31.5%)
total bindings lazily fixed up: 0 of 0
total time in initializers and ObjC +load: 163.24 milliseconds (9.8%)
libSystem.B.dylib : 7.98 milliseconds (0.4%)
libBacktraceRecording.dylib : 13.53 milliseconds (0.8%)
libMainThreadChecker.dylib : 41.11 milliseconds (2.4%)
libViewDebuggerSupport.dylib : 6.68 milliseconds (0.4%)
TestDemo : 88.76 milliseconds (5.3%)
total symbol trie searches: 1306942
total symbol table binary searches: 0
total images defining weak symbols: 41
total images using weak symbols: 105
main() 函数之后
手动插入代码,进行耗时计算。
// 第一步:在 main() 函数里用变量 MainStartTime 记录当前时间
CFAbsoluteTime MainStartTime;
int main(int argc, char * argv[]) {
MainStartTime = CFAbsoluteTimeGetCurrent();
@autoreleasepool {
return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class]));
}
}
// 第二步:在 AppDelegate.m 文件中用 extern 声明全局变量 MainStartTime
extern CFAbsoluteTime MainStartTime;
// 第三步:在 didFinishLaunchingWithOptions 方法结束前,再获取一下当前时间,与 MainStartTime 的差值就是 main() 函数阶段的耗时
double mainLaunchTime = (CFAbsoluteTimeGetCurrent() - MainStartTime);
NSLog(@"main() 阶段耗时:%.2fms", mainLaunchTime * 1000);
网友评论