Skip to content

Instantly share code, notes, and snippets.

@pofat
Created February 16, 2020 14:23
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pofat/f13f057fa587cfebe29f7a65547cb7c8 to your computer and use it in GitHub Desktop.
Save pofat/f13f057fa587cfebe29f7a65547cb7c8 to your computer and use it in GitHub Desktop.
Get pre-main time
/// Call this at main()
/// return: time in milliseconds
func getPreMainTime() -> Double {
let currentTimeIntervalInMilliSecond = Date().timeIntervalSince1970 * 1000.0
var procInfo = kinfo_proc()
let pid = ProcessInfo.processInfo.processIdentifier
var cmd: [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, pid]
var size = MemoryLayout.stride(ofValue: procInfo)
// Retrieve information of current process
if sysctl(&cmd, UInt32(cmd.count), &procInfo, &size, nil, 0) == 0 {
// tv_sec -> timestamp in second; tv_usec -> rest fraction part in microsecond
let tvSecInMilliseconds = Double(procInfo.kp_proc.p_un.__p_starttime.tv_sec) * 1000.0
let tvUsecInMilliseconds = Double(procInfo.kp_proc.p_un.__p_starttime.tv_usec) / 1000.0
let processCreationTime = tvSecInMilliseconds + tvUsecInMilliseconds
var premainTime = currentTimeIntervalInMilliSecond - processCreationTime
premainTime.round()
return premainTime
} else {
print("Can't retrieve information of process", category: .perfLogger)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment