Python Popen 函数等价于 Java ProcessBuilder.start() 方法。
在上面的示例中,您将 Jvm 用于子进程 complete 的时间与 Python 用于子进程 start 的时间进行比较。
要比较相同的东西,你应该比较:
JVM
// Start subprocess
val processHandle = ProcessBuilder("node", "someFile.js").start()
// Wait subprocess to terminate
val returnCode = processHandle.waitFor()
到
Python
# Start subprocess
val processHandle = subprocess.Popen(["node", "someFile.js")
# Wait subprocess to terminate
val returnCode = processHandle.wait()
编辑
我在笔记本电脑上运行了简单的测试,但我没有发现 Kotlin 和 Python 之间的性能有显着差异。我会把它放在这里作为测试依据,即使措施没有“正确”完成(通过 JMH for Kotlin),它也给出了一个想法:
科特林
所以,对于 Kotlin,我制作了以下 .kts 脚本:
import java.lang.ProcessBuilder;
fun main() {
var started : Long = 0
var completed : Long = 0
for (i in 0 until 1000) {
val start = System.nanoTime()
val process = ProcessBuilder("ls").start()
started += (System.nanoTime() - start)
process.waitFor()
completed += (System.nanoTime() - start)
}
println("Average time (ms) to start a process: ${started * 1e-9}")
println("Average time (ms) to complete a started process: ${completed * 1e-9}")
}
在 jre 10 上加载 Kotlin REPL 1.4.21 后,我得到以下输出:
Average time (ms) to start a process: 0.667509729
Average time (ms) to complete a started process: 5.042644314
Python
在 Python 3.7.9 上,以下脚本:
import subprocess
from time import perf_counter_ns
started = 0
completed = 0
for i in range(0, 1000):
start = perf_counter_ns()
process = subprocess.Popen("ls")
started += (perf_counter_ns() - start)
process.wait()
completed += (perf_counter_ns() - start)
print("Average time (ms) to start a process: ", started * 1e-9)
print("Average time (ms) to complete a process: ", completed * 1e-9)
输出:
Average time (ms) to start a process: 1.620647841
Average time (ms) to complete a process: 6.208644367000001
所以,我目前的想法是,一旦执行上下文准备好,这两种方法之间的性能应该不会有太大差距。因此,如果您注意到很大的差异,则问题可能是由于子流程之外的一些代码或初始化引起的。
此时,需要更多细节(一个最小的可重现示例是最好的)才能找到正确答案。