I get app thread start time via sysctl. Then, when the app starts in the background (such as receiving an incoming call), I calculate the preMain duration of the app. Most of the time, the data is normal (hundreds of milliseconds). But occasionally a very large duration (such as tens of seconds) appears. It feels like restarting the mobile phone test has a higher probability.
// Code in main.swift
let appStartLaunchTime: CFAbsoluteTime = CFAbsoluteTimeGetCurrent()
// Calculate preMain time
var preMain = appStartLaunchTime - appLaunchTime! + kCFAbsoluteTimeIntervalSince1970
public var appLaunchTime: Double? = {
var processInfo = kinfo_proc()
var size = MemoryLayout<kinfo_proc>.stride
var mib: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
guard sysctl(&mib, u_int(mib.count), &processInfo, &size, nil, 0) == 0 else {
return nil
}
let startTime = processInfo.kp_proc.p_starttime
let time = (Int64(startTime.tv_sec) * 1000) + Int64(startTime.tv_usec / 1000)
return Double(time) / 1000.0
}()