首页 > 解决方案 > 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

标签: pythonlinuxmultiprocessingpool

解决方案


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


推荐阅读