来自 Python 多处理池 Class 的意外行为

Unexpected Behavior from Python Multiprocessing Pool Class

我正在尝试利用 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

multiprocessing.Poolapply 函数只是 运行 一个单独进程中的函数,并等待其结果。它需要比 运行ning 多一点的顺序,因为它需要打包要处理的作业并通过 pipe.

将其发送到子进程

multiprocessing 不会使顺序操作更快,如果您的硬件有多个内核,它只是允许它们 运行 并行。

试试这个:

urls = ["http://google.com", 
        "http://example.com", 
        "http://whosebug.com", 
        "http://python.org"]

results = pool.map(stress_test_url, urls)

您会看到这 4 个网址似乎同时被访问。这意味着您的逻辑将访问 N 个网站所需的时间减少到 N / processes.

最后,对执行 HTTP 请求的函数进行基准测试是衡量性能的一种非常糟糕的方法,因为网络不可靠。无论您是否使用 multiprocessing ,您都很难获得花费相同时间的两次执行。