首页 > 解决方案 > 在 4 个 CPU 上执行 CPU 密集型任务时,20 个进程中的 400 个线程优于 4 个进程中的 400 个线程

问题描述

这个问题与执行 I/O-bound 任务时 20 个进程中的 400 个线程优于 4 个进程中的 400 个线程非常相似。唯一的区别是链接的问题是关于 I/O-bound 任务,而这个问题是关于 CPU-bound 任务。

实验代码

这是一个实验代码,可以启动指定数量的工作进程,然后在每个进程内启动指定数量的工作线程,并执行计算第n个素数的任务。

import math
import multiprocessing
import random
import sys
import time
import threading

def main():
    processes = int(sys.argv[1])
    threads = int(sys.argv[2])
    tasks = int(sys.argv[3])

    # Start workers.
    in_q = multiprocessing.Queue()
    process_workers = []
    for _ in range(processes):
        w = multiprocessing.Process(target=process_worker, args=(threads, in_q))
        w.start()
        process_workers.append(w)

    start_time = time.time()

    # Feed work.
    for nth in range(1, tasks + 1):
        in_q.put(nth)

    # Send sentinel for each thread worker to quit.
    for _ in range(processes * threads):
        in_q.put(None)

    # Wait for workers to terminate.
    for w in process_workers:
        w.join()

    total_time = time.time() - start_time
    task_speed = tasks / total_time

    print('{:3d} x {:3d} workers => {:6.3f} s, {:5.1f} tasks/s'
          .format(processes, threads, total_time, task_speed))



def process_worker(threads, in_q):
    thread_workers = []
    for _ in range(threads):
        w = threading.Thread(target=thread_worker, args=(in_q,))
        w.start()
        thread_workers.append(w)

    for w in thread_workers:
        w.join()


def thread_worker(in_q):
    while True:
        nth = in_q.get()
        if nth is None:
            break
        num = find_nth_prime(nth)
        #print(num)


def find_nth_prime(nth):
    # Find n-th prime from scratch.
    if nth == 0:
        return

    count = 0
    num = 2
    while True:
        if is_prime(num):
            count += 1

        if count == nth:
            return num

        num += 1


def is_prime(num):
    for i in range(2, int(math.sqrt(num)) + 1):
        if num % i == 0:
            return False
    return True


if __name__ == '__main__':
    main()

这是我运行这个程序的方式:

python3 foo.py <PROCESSES> <THREADS> <TASKS>

例如,python3 foo.py 20 20 2000创建 20 个工作进程,每个工作进程中有 20 个线程(因此总共有 400 个工作线程)并执行 2000 个任务。最后,该程序会打印出执行任务所需的时间以及平均每秒执行的任务数。

环境

我正在具有 8 GB RAM 和 4 个 CPU 的 Linode 虚拟专用服务器上测试此代码。它正在运行 Debian 9。

$ cat /etc/debian_version 
9.9

$ python3
Python 3.5.3 (default, Sep 27 2018, 17:25:39) 
[GCC 6.3.0 20170516] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 

$ free -m
              total        used        free      shared  buff/cache   available
Mem:           7987          67        7834          10          85        7734
Swap:           511           0         511

$ nproc
4

案例 1:20 个进程 x 20 个线程

以下是一些在 20 个工作进程之间分布的 400 个工作线程的试运行(即,20 个工作进程中的每个工作线程中有 20 个工作线程)。

结果如下:

$ python3 bar.py 20 20 2000
 20 x  20 workers => 12.702 s, 157.5 tasks/s

$ python3 bar.py 20 20 2000
 20 x  20 workers => 13.196 s, 151.6 tasks/s

$ python3 bar.py 20 20 2000
 20 x  20 workers => 12.224 s, 163.6 tasks/s

$ python3 bar.py 20 20 2000
 20 x  20 workers => 11.725 s, 170.6 tasks/s

$ python3 bar.py 20 20 2000
 20 x  20 workers => 10.813 s, 185.0 tasks/s

当我使用top命令监控 CPU 使用率时,我看到每个python3工作进程消耗大约 15% 到 25% 的 CPU。

案例 2:4 个进程 x 100 个线程

现在我以为我只有 4 个 CPU。即使我启动 20 个工作进程,在物理时间的任何时间点最多也只有 4 个进程可以运行。此外,由于全局解释器锁 (GIL),每个进程中只有一个线程(因此最多总共 4 个线程)可以在物理时间的任何点运行。

因此,我想如果我将进程数减少到 4,并将每个进程的线程数增加到 100,这样总线程数仍然保持在 400,性能应该不会恶化。

但是测试结果表明,每个包含 100 个线程的 4 个进程的性能始终比每个包含 20 个线程的 20 个进程差。

$ python3 bar.py 4 100 2000
  4 x 100 workers => 19.840 s, 100.8 tasks/s

$ python3 bar.py 4 100 2000
  4 x 100 workers => 22.716 s,  88.0 tasks/s

$ python3 bar.py 4 100 2000
  4 x 100 workers => 20.278 s,  98.6 tasks/s

$ python3 bar.py 4 100 2000
  4 x 100 workers => 19.896 s, 100.5 tasks/s

$ python3 bar.py 4 100 2000
  4 x 100 workers => 19.876 s, 100.6 tasks/s

每个python3工作进程的 CPU 使用率在 50% 到 66% 之间。

案例 3:1 个进程 x 400 个线程

只是为了比较,我记录了一个事实,即案例 1 和案例 2 都优于我们在单个进程中拥有所有 400 个线程的情况。这显然是由于全局解释器锁 (GIL)。

$ python3 bar.py 1 400 2000
  1 x 400 workers => 34.762 s,  57.5 tasks/s

$ python3 bar.py 1 400 2000
  1 x 400 workers => 35.276 s,  56.7 tasks/s

$ python3 bar.py 1 400 2000
  1 x 400 workers => 32.589 s,  61.4 tasks/s

$ python3 bar.py 1 400 2000
  1 x 400 workers => 33.974 s,  58.9 tasks/s

$ python3 bar.py 1 400 2000
  1 x 400 workers => 35.429 s,  56.5 tasks/s

python3单个工作进程的 CPU 使用率介于 110% 和 115% 之间。

案例 4:400 个进程 x 1 个线程

同样,为了比较,这里是当有 400 个进程时的结果,每个进程都有一个线程。

$ python3 bar.py 400 1 2000
400 x   1 workers =>  8.814 s, 226.9 tasks/s

$ python3 bar.py 400 1 2000
400 x   1 workers =>  8.631 s, 231.7 tasks/s

$ python3 bar.py 400 1 2000
400 x   1 workers => 10.453 s, 191.3 tasks/s

$ python3 bar.py 400 1 2000
400 x   1 workers =>  8.234 s, 242.9 tasks/s

$ python3 bar.py 400 1 2000
400 x   1 workers =>  8.324 s, 240.3 tasks/s

每个python3工作进程的 CPU 使用率在 1% 到 3% 之间。

概括

从每个案例中选取中值结果,我们得到以下摘要:

Case 1:  20 x  20 workers => 12.224 s, 163.6 tasks/s
Case 2:   4 x 100 workers => 19.896 s, 100.5 tasks/s
Case 3:   1 x 400 workers => 34.762 s,  57.5 tasks/s
Case 4: 400 x   1 workers =>  8.631 s, 231.7 tasks/s

问题

为什么即使我只有 4 个 CPU,20 进程 x 20 线程的性能也优于 4 进程 x 100 线程?

事实上,尽管只有 4 个 CPU,但 400 个进程 x 1 个线程的性能最好?为什么?

标签: pythonmultithreadingperformancemultiprocessinggil

解决方案


在 Python 线程可以执行代码之前,它需要获取全局解释器锁 (GIL)。这是一个进程锁。在某些情况下(例如,当等待 I/O 操作完成时)一个线程会定期释放 GIL,以便其他线程可以获取它。如果活动线程在一定时间内没有放弃锁,则其他线程可以向活动线程发出信号以释放 GIL,以便它们轮流执行。

考虑到这一点,让我们看看您的代码在我的 4 核笔记本电脑上的执行情况:

  1. 在最简单的情况下(1 个进程和 1 个线程)我得到约 155 个任务/秒。GIL 不会妨碍我们。我们使用 100% 的一个核心。

  2. 如果我增加线程数(1 个进程有 4 个线程),我会得到约 70 个任务/秒。一开始这可能违反直觉,但可以通过以下事实来解释:您的代码主要受 CPU 限制,因此所有线程几乎一直都需要 GIL。一次只有一个可以运行它的计算,所以我们不能从多线程中受益。结果是我们使用了我的 4 个内核中的大约 25%。更糟糕的是,获取和释放 GIL 以及上下文切换会增加大量开销,从而降低整体性能。

  3. 添加更多线程(1 个具有 400 个线程的进程)并没有帮助,因为一次只执行其中一个。在我的笔记本电脑上,性能与案例 (2) 非常相似,我们再次使用了 4 个内核中的大约 25%。

  4. 有 4 个进程,每个进程有 1 个线程,我得到约 550 个任务/秒。几乎是我在案例(1)中得到的 4 倍。实际上,由于进程间通信和锁定共享队列所需的开销,会少一点。请注意,每个进程都使用自己的 GIL。

  5. 4 个进程每个运行 100 个线程,我得到约 290 个任务/秒。我们再次看到我们在 (2) 中看到的减速,这一次影响了每个单独的进程。

  6. 400 个进程每个运行 1 个线程,我得到约 530 个任务/秒。与(4)相比,由于进程间通信和共享队列上的锁定,我们看到了额外的开销。

有关这些效果的更深入解释,请参阅David Beazley 的演讲 了解 Python GIL 。

注意:一些 Python 解释器(如 CPython 和 PyPy)有 GIL,而其他解释器(如 Jython 和 IronPython)没有。如果您使用另一个 Python 解释器,您可能会看到非常不同的行为。


推荐阅读