Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

waitUntilExit cause slow execution #101

Open
leavez opened this issue Mar 4, 2021 · 1 comment
Open

waitUntilExit cause slow execution #101

leavez opened this issue Mar 4, 2021 · 1 comment

Comments

@leavez
Copy link

leavez commented Mar 4, 2021

I benchmark the duration of executing a simple process. On other languages (ruby, go, bash), the result is about 1ms, but on Swift, it takes about 60ms.

The test code is

let s = Date()
SwiftShell.run("/bin/cp")
print(Date().IntervalSince(s))

I also test with raw Process and get same result

let s2 = Date()
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/cp")
try process.run()
process.waitUntilExit()
print(Date().IntervalSince(s2))

After digging, I found the it may cause by the Process.waitUntilExit:

 "it polls the current run loop using NSDefaultRunLoopMode until the task completes"

https://developer.apple.com/documentation/foundation/nstask/1415808-waituntilexit

When changing it to terminationHandler, it's back to normal.

let s2 = Date()
let process = Process()
process.executableURL = URL(fileURLWithPath: "/bin/cp")
process.terminationHandler = { t in
    print(2, Date().timeIntervalSince(s2))
}
try process.run()
process.waitUntilExit()
print(1, Date().timeIntervalSince(s2))

The output:

2 0.007783055305480957
1 0.06369709968566895
@kareman
Copy link
Owner

kareman commented Mar 8, 2021

Nice finding. Any reimplementation of SwiftShell.run using terminationHandler is welcome :)

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

No branches or pull requests

2 participants