多线程vs多进程
计算密集型
from threading import Thread
from multiprocessing import Process
import time
#计算密集型
def work1():
res=0
for i in range(100000000):
res*=i
if __name__ == '__main__':
t_list=[]
start=time.time()
for i in range(4):
# t=Thread(target=work1)
t=Process(target=work1)
t_list.append(t)
t.start()
for t in t_list:
t.join()
end=time.time()
# print('多线程',end-start) #多线程 20.864253044128418
print('多进程',end-start) #多进程 8.076735258102417
io密集型
from multiprocessing import Process
from threading import Thread
import time
#计算密集型
def work1():
x=1+1
time.sleep(5)
if __name__ == '__main__':
t_list=[]
start=time.time()
for i in range(4):
t=Thread(target=work1)
# t=Process(target=work1)
t_list.append(t)
t.start()
for t in t_list:
t.join()
end=time.time()
print('多线程',end-start) #多线程 5.002452373504639
# print('多进程',end-start) #多进程 5.937068939208984