python - 来自 Python 多处理池类的意外行为

标签 python linux multiprocessing pool

我正在尝试利用 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 函数只是在单独的进程中运行一个函数并等待其结果。它需要比顺序运行多一点,因为它需要打包要处理的作业并通过 pipe 将其发送到子进程。

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

试试这个:

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

results = pool.map(stress_test_url, urls)

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

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

关于python - 来自 Python 多处理池类的意外行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51409202/

相关文章:

python - 如何使用 python-pandas 同时分解两个数据框?

linux - 如何对二进制格式的数字数据使用 GNU 排序?

linux - 打开在 docker 容器(Alpine)中创建的 pdf 文件

android - 一段时间后 Adb 停止检测我的手机

Python - 使用多处理时的多个输出副本

python - 当 python 列表迭代是和不是引用时

python - 如何将自动过滤器添加到与 SQLAlchemy 的关系中?

python - 有趣的名称/不完整的附件/错误的扩展名 - Mail Python

python - python 中的多线程 : is it really performance effiicient most of the time?

python - 是否可以按顺序启动 Pool 进程?