从Python启动的子进程比从bash启动的运行慢

Muf*_*ffo 5 python bash benchmarking

我使用以下 Python 代码来运行子进程并将其输出收集为字符串:

def run(command):
    ''' Run a command and return the output as a string '''
    args = shlex.split(command)
    out = subprocess.Popen(args,
            stdout=subprocess.PIPE, stderr=subprocess.PIPE).communicate()[0]

    # Save to log file
    with open("log_file.txt", "a") as log_file:
        log_file.write("$ " + command + "\n")
        log_file.write(out)

    return out
Run Code Online (Sandbox Code Playgroud)

我的目标是多次运行基准测试应用程序 ( openssl speed) 并使用 Python 解析输出并计算平均结果。

但是,我注意到结果始终比直接从 bash 命令行运行相同命令慢(大约 10%)。

你会如何解释这一点?

编辑

该命令的输出非常短:大约 10 行。另请注意,性能测试运行时基准测试不会打印任何输出。它只打印关键循环之外的结果。

在脚本中,我一次仅运行特定密码的基准测试,因此例如我使用以下参数:

openssl speed -elapsed -engine my_engine rsa2048
Run Code Online (Sandbox Code Playgroud)

请注意,我使用的是自定义引擎(基准测试的目标)而不是标准软件实现。我的引擎生成了另一个 pthread,但我不希望产生很大的差异,因为 Python 脚本不应该以任何方式进行交互。