直接用單線程執行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密集型而言,多線程沒特別大的優勢,和一個線程的執行時間相差不是特別大