# -*- coding: utf-8 -*-
import time
from multiprocessing import Process
from threading import Thread
def func():
ret = 0
for i in range(10000000):
ret += i
if __name__ == ‘__main__‘:
‘‘‘计算密集型‘‘‘
start_time = time.time()
p_lst = []
for i in range(10):
# p = Process(target=func)
p = Thread(target=func)
p_lst.append(p)
p.start()
[pp.join() for pp in p_lst]
end_time = time.time()
print("run time is :%s" % (end_time-start_time))
# run time is :3.555203437805176 # 多进程的运行时间,4个cpu同时处理
# run time is :9.960569858551025 # 多线程的运行时间,一个cpu去处理
# 多核计算密集型的,选择多进程,可以充分利用cpu
# -*- coding: utf-8 -*-
import time
from multiprocessing import Process
from threading import Thread
def func():
time.sleep(1)
if __name__ == ‘__main__‘:
‘‘‘IO密集型‘‘‘
start_time = time.time()
p_lst = []
for i in range(10):
# p = Process(target=func)
p = Thread(target=func)
p_lst.append(p)
p.start()
[pp.join() for pp in p_lst]
end_time = time.time()
print("run time is :%s" % (end_time-start_time))
# run time is :1.660094976425171 # 多进程的运行时间,4个cpu同时处理,因为进程比线程的开销大
# run time is :1.0020575523376465 # 多线程的运行时间,一个cpu去处理
# 多核IO密集型的,选择多线程,线程开销小
原文:https://www.cnblogs.com/lilyxiaoyy/p/11026015.html