Skip to content

Instantly share code, notes, and snippets.

@DenTelezhkin
Last active May 21, 2024 13:40
Show Gist options
  • Save DenTelezhkin/d57c3839cf0773ffe666dce9e58c7fa3 to your computer and use it in GitHub Desktop.
Save DenTelezhkin/d57c3839cf0773ffe666dce9e58c7fa3 to your computer and use it in GitHub Desktop.
Measure iOS app startup time, in seconds, from the time user tapped an icon on the home screen (using time, when app process was created). Swift 4.
// Returns number of seconds passed between time when process was created and function was called
func measureAppStartUpTime() -> Double {
var kinfo = kinfo_proc()
var size = MemoryLayout<kinfo_proc>.stride
var mib : [Int32] = [CTL_KERN, KERN_PROC, KERN_PROC_PID, getpid()]
sysctl(&mib, u_int(mib.count), &kinfo, &size, nil, 0)
let start_time = kinfo.kp_proc.p_starttime
var time : timeval = timeval(tv_sec: 0, tv_usec: 0)
gettimeofday(&time, nil)
let currentTimeMilliseconds = Double(Int64(time.tv_sec) * 1000) + Double(time.tv_usec) / 1000.0
let processTimeMilliseconds = Double(Int64(start_time.tv_sec) * 1000) + Double(start_time.tv_usec) / 1000.0
return (currentTimeMilliseconds - processTimeMilliseconds) / 1000.0
}
@akingdom
Copy link

akingdom commented Jul 28, 2022

Where do you call this function? In root view controller or somewhere else?

It doesn't matter where it is called from. Call it from where you need it. The code goes off and checks when the unix process was created (not when your view was created).

@DenTelezhkin
Copy link
Author

You should call this function as early as possible. If your app has main.swift, this would be a great place. If not, you can try calling it in your AppDelegate init (it’s also helpful to call it in applicationDidFinishLaunching to find out how long does your application start after process has been spawned).

@A-Dirt
Copy link

A-Dirt commented Nov 27, 2023

There is a problem with processTimeMilliseconds . Sometimes I get a wrong result, it is much earlier than the real launch time

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment