【Python】多进程与多线程的选择

# 对于计算密集型的任务,应该使用多进程(发挥CPU优势)

# 对于IO密集型的任务,应该采用多线程

from multiprocessing import Process
from threading import Thread
import threading
import os, time


def work(work_type):
if work_type == 2:
time.sleep(2)
elif work_type == 1:
res = 0
for i in range(100000000):
res *= i
print('stop')


if __name__ == '__main__':
l = []
work_type = 2
print(os.cpu_count())
start = time.time()
for i in range(400):
# p = Process(target=work, kwargs={'work_type': work_type}) # count 3.99s io 12.27s
p = Thread(target=work, kwargs={'work_type': work_type}) # count 15s io 2.0039s
l.append(p)
p.start()

for p in l:
p.join()

stop = time.time()
print(stop-start)
posted @ 2018-08-26 18:00  caya  阅读(263)  评论(0编辑  收藏  举报