gil 在CPU密集型多線程和單線程執行效率對比

直接用單線程執行for循環,執行5次,計算執行的時間

import logging
import datetime

FORMAT = '%(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

start = datetime.datetime.now()

def calc():
    sum = 0
    for _ in range(100000000):
        sum += 1

calc()
calc()
calc()
calc()
calc()

delta = (datetime.datetime.now() - start).total_seconds()
logging.info(delta)

用多線程的方式,同樣的for循環,使用5個線程跑,統計執行的時間

import threading
import logging
import datetime

FORMAT = '%(threadName)s %(thread)d %(message)s'
logging.basicConfig(format=FORMAT, level=logging.INFO)

start = datetime.datetime.now()

def calc():
    sum = 0
    for _ in range(100000000000):
        sum += 1
lst = []
for i in range(5):
    t = threading.Thread(target=calc, )
    lst.append(t)
    t.start()

for i in lst:
    i.join()

delta = (datetime.datetime.now() - start).total_seconds()
logging.info(delta)

兩個測試結果來看,在CPython中,對於CPU密集型而言,多線程沒特別大的優勢,和一個線程的執行時間相差不是特別大

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章