python - Python 多处理池类的意外行为
问题描述
我正在尝试利用 Python 的多处理库来使用我在我创建的 Linux VM 上拥有的 8 个处理核心快速运行一个函数。作为测试,我得到了具有 4 个进程的工作池运行一个函数所需的时间(以秒为单位),以及在不使用工作池的情况下运行相同函数所需的时间。以秒为单位的时间大致相同,在某些情况下,处理工作池的时间比没有处理要长得多。
脚本
import requests
import datetime
import multiprocessing as mp
shared_results = []
def stress_test_url(url):
print('Starting Stress Test')
count = 0
while count <= 200:
response = requests.get(url)
shared_results.append(response.status_code)
count += 1
pool = mp.Pool(processes=4)
now = datetime.datetime.now()
results = pool.apply(stress_test_url, args=(url,))
diff = (datetime.datetime.now() - now).total_seconds()
now = datetime.datetime.now()
results = stress_test_url(url)
diff2 = (datetime.datetime.now() - now).total_seconds()
print(diff)
print(diff2)
终端输出
Starting Stress Test
Starting Stress Test
44.316212
41.874116
解决方案
apply
函数只是在单独的multiprocessing.Pool
进程中运行一个函数并等待其结果。它需要比顺序运行多一点的时间,因为它需要打包要处理的作业并通过pipe
.
multiprocessing
不会使顺序操作更快,如果您的硬件具有多个内核,它只是允许它们并行运行。
试试这个:
urls = ["http://google.com",
"http://example.com",
"http://stackoverflow.com",
"http://python.org"]
results = pool.map(stress_test_url, urls)
您会看到这 4 个 URL 似乎同时被访问。这意味着您的逻辑将访问 N 个网站所需的时间减少到 N / processes
。
最后,对执行 HTTP 请求的函数进行基准测试是衡量性能的一种非常糟糕的方法,因为网络不可靠。无论您是否使用,您几乎都不会执行两次花费相同时间的执行multiprocessing
。
推荐阅读
- google-cloud-platform - 创建谷歌计算实例组给我的 terraform 错误,但已创建
- excel - Excel VBA,如果其他工作表上的相应值显示“创建”,则在相邻单元格中添加“是”
- jquery - 如何摆脱底部的这个空白?
- javascript - Javascript 或 Rails:如何获取 BLE 设备或蓝牙
- javascript - 如何对我的徽标产生影响?
- nav - 停止导航/侧边栏滚动
- javascript - FullCalendar HTML5 Drag & Drop Api
- java - JBoss EAP 5.1 - 缓慢的部署启动
- vbscript - 尝试打开新的 SAP 会话时 VBscript 有条件?
- postgresql - 在 postgresql 的 WITH 查询中使用 EXECUTE