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