进程池、线程池、单线程 运行时间实验
"""
进程池、线程池、单线程、
CPU密集型、IO密集型、的速度对比
CPU密集型:需要CPU进行复杂运算的情况
IO密集型:需要频繁进程读写数据的情况
实验结论:
CPU密集型 多进程 或者 进程池
IO密集型 多线程 或者 线程池
无需并发 单个线程
"""
from multiprocessing import Pool
from concurrent.futures import ThreadPoolExecutor, as_completed
import time
def fun1(n):
num = []
for i in range(2, n):
for j in range(2, i):
if i % j == 0:
break
else:
num.append(i)
return num
def fun2(n):
fo = open("测试IO密集型文件.txt", "w")
fo.write("A" * n * 1000)
time.sleep(1)
fo.close()
return True
if __name__ == '__main__':
fun = fun2
t1 = time.time()
p = Pool(3)
res_l = []
for i in [9999, 9999, 9999]:
res = p.apply_async(fun, args=(i,))
res_l.append(res)
p.close()
p.join()
for res in res_l:
print(res.get())
t2 = time.time()
print("进程池运行时间", t2 - t1)
t3 = time.time()
l = []
urls = [9999, 9999, 9999]
with ThreadPoolExecutor() as pool:
f = [pool.submit(fun, url) for url in urls]
for j in as_completed(f):
l.append(j.result())
print(l)
t4 = time.time()
print("线程池运行时间", t4 - t3)
t5 = time.time()
res_ = []
for i in [9999, 9999, 9999]:
res_.append(fun(i))
print(res_)
t6 = time.time()
print("正常单个运行时间", t6 - t5)