Python 多进程行为,进程数大于核心数

2024-06-02 08:47:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试使用Python的multiprocessing库,并希望了解它在不同进程数下的行为

我假设设置大于核心数量的进程没有任何好处。与假设相反,下面的实验代码表明,即使进程数超过了内核数(在我的例子中为4),计算时间也会减少

有人能解释一下幕后发生了什么,并就如何设置进程的数量提供一些实用的指导吗

from multiprocessing import Pool, cpu_count
import time
from datetime import datetime

我的CPU计数

cpu_count()
# 4

一项实验任务,大约需要0.5秒

def f(x):
    time.sleep(0.5)
    return x*x

def execute_time(processes):
    t1 = datetime.now()
    with Pool(processes) as p:
        p.map(f, list(range(36)))
    t2 = datetime.now()
    return t2 - t1

for p in range(1, 25):
    t = execute_time(p)
    print(p, ":", t)

产生:

# 1 : 0:00:18.065411
# 2 : 0:00:10.051516
# 3 : 0:00:06.057016
# 4 : 0:00:04.562439
# 5 : 0:00:04.069810
# 6 : 0:00:03.173502
# 7 : 0:00:03.065977
# 8 : 0:00:03.082625
# 9 : 0:00:02.092880
# 10 : 0:00:02.090963
# 11 : 0:00:02.061613
# 12 : 0:00:01.704716
# 13 : 0:00:01.704880
# 14 : 0:00:01.615440
# 15 : 0:00:01.625117
# 16 : 0:00:01.621259
# 17 : 0:00:01.639741
# 18 : 0:00:01.236108
# 19 : 0:00:01.250113
# 20 : 0:00:01.255697
# 21 : 0:00:01.253459
# 22 : 0:00:01.260632
# 23 : 0:00:01.262124
# 24 : 0:00:01.247772

一个进程执行该函数需要18秒(36*0.5秒=18秒)是有道理的。四个过程的情况也是如此(18秒/4=4.5秒)。但我感到惊讶的是,计算时间随着进程数量的增加而减少


Tags: fromimportexecute数量datetimereturntime进程
1条回答
网友
1楼 · 发布于 2024-06-02 08:47:19

正如Michael Butscher在评论中所说,这是sleep的一种特殊行为。对于CPU密集型任务,我发现好处是有限的,进程数等于核心数

def f(x):
    out = 0
    for i in range(5000000):
        out += i
    return x*x

def execute_time(processes):
    t1 = datetime.now()
    with Pool(processes) as p:
        p.map(f, list(range(36)))
    t2 = datetime.now()
    return t2 - t1

for p in range(1, 25):
    t = execute_time(p)
    print(p, ":", t)

获取:

# 1 : 0:00:13.329320
# 2 : 0:00:07.528552
# 3 : 0:00:09.943043
# 4 : 0:00:07.756005
# 5 : 0:00:08.262304
# 6 : 0:00:07.653659
# 7 : 0:00:07.677038
# 8 : 0:00:07.591766
# 9 : 0:00:07.502283
# 10 : 0:00:07.710826
# 11 : 0:00:06.006874
# 12 : 0:00:09.720279
# 13 : 0:00:07.912836
# 14 : 0:00:07.616807
# 15 : 0:00:07.740225
# 16 : 0:00:07.721783
# 17 : 0:00:07.836259
# 18 : 0:00:07.665993
# 19 : 0:00:07.564645
# 20 : 0:00:07.653607
# 21 : 0:00:07.754377
# 22 : 0:00:07.886036
# 23 : 0:00:11.696323
# 24 : 0:00:07.674243

相关问题 更多 >