Pythonはインタプリタ上で動作する言語です。調べたところ、Pythonにはグローバルロック(GIL)があり、マルチスレッド(Thread)を使用した場合、マルチコアの利点を活かせません。一方、マルチプロセス(Multiprocess)を使用すれば、マルチコアの利点を活かして本当に効率を向上させることができます。

比較実験

資料によると、マルチスレッドのプロセスがCPU集約型の場合、マルチスレッドでは効率の向上をあまり期待できず、逆にスレッドの頻繁な切り替えによって効率が低下する可能性があるため、マルチプロセスの使用を推奨します。もしIO密集型の場合、マルチスレッドのプロセスはIOブロック待ちのアイドル時間を利用して他のスレッドを実行し、効率を向上させることができます。そこで、実験によって異なるシナリオの効率を比較します

オペレーティングシステム CPU メモリ ハードディスク
Windows 10 デュアルコア 8GB 機械式ハードディスク

(1)必要なモジュールを導入する

import requests
import time
from threading import Thread
from multiprocessing import Process

(2)CPU密集型の計算関数を定義する

def count(x, y):
    # 使程序完成50万计算
    c = 0
    while c < 500000:
        c += 1
        x += x
        y += y

(3)IO密集型のファイル読み書き関数を定義する

def write():
    f = open("test.txt", "w")
    for x in range(5000000):
        f.write("testwrite\n")
    f.close()
def read():
    f = open("test.txt", "r")
    lines = f.readlines()
    f.close()

(4)ネットワークリクエスト関数を定義する

_head = {
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/48.0.2564.116 Safari/537.36'}
url = "http://www.tieba.com"
def http_request():
    try:
        webPage = requests.get(url, headers=_head)
        html = webPage.text
        return {"context": html}
    except Exception as e:
        return {"error": e}

(5)IO密集操作、CPU密集操作、ネットワークリクエスト密集操作を線形実行するのに必要な時間をテストする

# CPU密集操作
t = time.time()
for x in range(10):
    count(1, 1)
print("Line cpu", time.time() - t)
# IO密集操作
t = time.time()
for x in range(10):
    write()
    read()
print("Line IO", time.time() - t)
# 网络请求密集型操作
t = time.time()
for x in range(10):
    http_request()
print("Line Http Request", time.time() - t)

出力

  • CPU密集:95.6059999466、91.57099986076355 92.52800011634827、 99.96799993515015

  • IO密集:24.25、21.76699995994568、21.769999980926514、22.060999870300293

  • ネットワークリクエスト密集型:4.519999980926514、8.563999891281128、4.371000051498413、4.522000074386597、14.671000003814697

(6)マルチスレッドでCPU密集操作を並行実行するのに必要な時間をテストする

counts = []
t = time.time()
for x in range(10):
    thread = Thread(target=count, args=(1,1))
    counts.append(thread)
    thread.start()
e = counts.__len__()
while True:
    for th in counts:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print(time.time() - t)

Output: 25.69700002670288、24.02400016784668

(7)マルチスレッドでIO密集操作を並行実行するのに必要な時間をテストする

def io():
    write()
    read()

t = time.time()
ios = []
t = time.time()
for x in range(10):
    thread = Thread(target=count, args=(1,1))
    ios.append(thread)
    thread.start()

e = ios.__len__()
while True:
    for th in ios:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print(time.time() - t)

Output: 99.9240000248 、101.26400017738342、102.32200002670288

(8)マルチスレッドでネットワーク密集操作を並行実行するのに必要な時間をテストする

t = time.time()
ios = []
t = time.time()
for x in range(10):
    thread = Thread(target=http_request)
    ios.append(thread)
    thread.start()

e = ios.__len__()
while True:
    for th in ios:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print("Thread Http Request", time.time() - t)

Output: 0.7419998645782471、0.3839998245239258、0.3900001049041748

(9)マルチプロセスでCPU密集操作を並行実行するのに必要な時間をテストする

counts = []
t = time.time()
for x in range(10):
    process = Process(target=count, args=(1,1))
    counts.append(process)
    process.start()
e = counts.__len__()
while True:
    for th in counts:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print("Multiprocess cpu", time.time() - t)

Output: 54.342000007629395、53.437999963760376

(10)マルチプロセスでIO密集型操作を並行実行するテスト

t = time.time()
ios = []
t = time.time()
for x in range(10):
    process = Process(target=io)
    ios.append(process)
    process.start()

e = ios.__len__()
while True:
    for th in ios:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print("Multiprocess IO", time.time() - t)

Output: 12.509000062942505、13.059000015258789

(11)マルチプロセスでHttpリクエスト密集型操作を並行実行するテスト

t = time.time()
httprs = []
t = time.time()
for x in range(10):
    process = Process(target=http_request)
    ios.append(process)
    process.start()

e = httprs.__len__()
while True:
    for th in httprs:
        if not th.is_alive():
            e -= 1
    if e <= 0:
        break
print("Multiprocess Http Request", time.time() - t)

Output: 0.5329999923706055、0.4760000705718994

実験結果

CPU集約型操作 IO集約型操作 ネットワークリクエスト密集型操作
線形操作 94.91824996469 22.46199995279 7.3296000004
マルチスレッド操作 101.1700000762 24.8605000973 0.5053332647
マルチプロセス操作 53.8899999857 12.7840000391 0.5045000315

上記の結果から、次のことがわかります:

  • マルチスレッドはIO密集型の操作ではそれほど大きな利点がないように見えます(おそらくIO操作のタスクをもう少し重くすれば利点が現れるでしょう)。CPU密集型の操作では、シングルスレッドの線形実行よりも明らかにパフォーマンスが悪くなります。しかし、ネットワークリクエストのようなビジーウェイトでスレッドをブロックする操作では、マルチスレッドの利点が非常に顕著になります

  • マルチプロセスは、CPU密集型、IO密集型、およびネットワークリクエスト密集型(スレッドのブロックが頻繁に発生する操作)のいずれにおいても、パフォーマンスの利点を発揮できます。ただし、ネットワークリクエスト密集型のような操作では、マルチスレッドとほぼ同等でありながら、CPUなどのリソースをより多く消費します。そのため、このような場合にはマルチスレッドを選択して実行することができます

原文アドレス:http://blog.atomicer.cn/2016/09/30/Python%E4%B8%AD%E5%A4%9A%E7%BA%BF%E7%A8%8B%E5%92%8C%E5%A4%9A%E8%BF%9B%E7%A8%8B%E7%9A%84%E5%AF%B9%E6%AF%94/