并行运行多个 python 脚本

时间:2021-02-02 12:45:46

标签: python bash macos

为了测量并行处理单个与 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 上有多个内核可用/如何在专用内核上执行每个脚本以增加处理时间?

0 个答案:

没有答案