直接用单线程执行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密集型而言,多线程没特别大的优势,和一个线程的执行时间相差不是特别大
转载于:https://blog.51cto.com/windchasereric/2353462