代码之家  ›  专栏  ›  技术社区  ›  Kota Mori

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

  •  0
  • Kota Mori  · 技术社区  · 6 年前

    我正在尝试使用Python的 multiprocessing

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

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

    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
    

    1 回复  |  直到 6 年前
        1
  •  0
  •   Kota Mori    6 年前

    正如MichaelButscher在评论中所说,这是一种特殊的行为 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