iOS 获取启动时间

1,323 阅读1分钟

之前Xcode更新以后获取不到系统时间,答应给代码来着

结果一直有事情在忙,今天才贴,不好意思

LaunchTimer.h

#import <Foundation/Foundation.h>

NS_ASSUME_NONNULL_BEGIN

@interface LaunchTimer : NSObject

//didFinishLaunchingWithOptions 里调用
+ (void)launchTime;

@end

NS_ASSUME_NONNULL_END

LaunchTimer.m

#import "LaunchTimer.h"
#import <sys/sysctl.h>
#import <mach/mach.h>

// 创建进程时间
static double t1;
// before main()
static double t2;
// didFinishLaunchingWithOptions
static double t3;

@implementation LaunchTimer

/// 进程创建时间
double get_process_start_time(void) {
    if (t1 == 0) {
        struct kinfo_proc proc;
        int pid = [[NSProcessInfo processInfo] processIdentifier];
        int cmd[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, pid};
        size_t size = sizeof(proc);
        if (sysctl(cmd, sizeof(cmd)/sizeof(*cmd), &proc, &size, NULL, 0) == 0) {
            t1 = proc.kp_proc.p_un.__p_starttime.tv_sec * 1000.0 +
                 proc.kp_proc.p_un.__p_starttime.tv_usec / 1000.0;
        }
    }
    return t1;
}

void static __attribute__((constructor)) before_main() {
    if (t2 == 0) {
        t2 = CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970;
    }
}

///在didFinishLaunchingWithOptions中调用
+ (void)launchTime {
    double t1 = get_process_start_time();
    dispatch_async(dispatch_get_main_queue(), ^{
        if (t3 == 0) {
            t3 = CFAbsoluteTimeGetCurrent() + kCFAbsoluteTimeIntervalSince1970;
        }
        
        double pret = t2 - t1 / 1000;
        double didfinish = t3 - t2;
        double total = t3 - t1 / 1000;
        
        NSLog(@"启动耗时 pre-main: %f", pret);
        NSLog(@"启动耗时 didfinish: %f", didfinish);
        NSLog(@"启动耗时 total: %f", total);
    });
}

@end