首页 > 解决方案 > 并行运行多个 python 脚本

问题描述

为了并行测量单个与 7 个 python 脚本的处理时间,我执行了以下测试

我执行下面的代码,命名为 summer.py 作为 python 脚本:

python3 summer.py

Summer.py 源代码:

import timeit

start_time = timeit.default_timer()
num = 100000000

sum = 0
while (num > 0):
    sum += num
    num -= 1
elapsed = timeit.default_timer() - start_time
print("The sum is", sum)
print('elapsed is' , elapsed)

此脚本在 14 秒内执行,因此按顺序运行此脚本 7 次大约需要 14 秒 * 7 = 98 秒才能完成。

使用以下命令并行启动脚本 7 次:

nohup python3 summer.py > 1.txt &
nohup python3 summer.py > 2.txt &
nohup python3 summer.py > 3.txt &
nohup python3 summer.py > 4.txt &
nohup python3 summer.py > 5.txt &
nohup python3 summer.py > 6.txt &
nohup python3 summer.py > 7.txt &

我手动运行上述每个命令,所以这是一个有点粗略的衡量标准。每个脚本的执行时间如下:16、17、19、22、22、20、18。所有脚本完成执行的时间为 22 秒,这是所有脚本的最大执行时间。

运行 7 个程序实例,顺序运行大约需要 98 秒,而从命令行并行运行需要 22 秒。发生了什么并行性以允许每个进程并行运行?作为为每个 python 进程创建的新 GIL,这允许共享底层 CPU 吗?如果 CPU 上有多个内核可用/如何在专用内核上执行每个脚本以增加处理时间?

标签: pythonbashmacos

解决方案


推荐阅读