python - 并行运行多个 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 上有多个内核可用/如何在专用内核上执行每个脚本以增加处理时间?
解决方案
推荐阅读
- python - Python:列出您的平台支持的“格式代码”日期?
- android - 如何使用旧 api(如 16)构建 android 应用程序?
- python - 如何使用 matplotlib 在 Pandas 中绘制两个元组列表?
- python - 分层图表中每个图表对应的不同颜色?
- docker - 为什么我用 Click 库编写的这个 CLI 应用程序不能正常工作?
- sql-server - SQL 高 CPU 使用率(SharePoint 查询)
- css - 如何覆盖引导表行背景颜色
- google-cloud-pubsub - PubSubLite:跨区域访问 PubSub Lite
- javascript - Laravel 无限滚动并从 Api 获取数据
- django - URL中PK后的Django忽略字符串