1、多进程多进程:

优点:可以利用多核优势

缺点:开销大

2 、多线程:

优点:开销小

缺点:不能利用多核优势

3、结论:计算密集型可以选择多进程,IO密集型可以选择多线程

from threading import Thread
from multiprocessing import Process
import time
#计算密集型
def work():
    res=1
    for i in range(100000000):
        res+=i

if __name__ == '__main__':
    p_l=[]
    start=time.time()
    for i in range(4):
        # p=Process(target=work) #6.7473859786987305
        p=Thread(target=work) #24.466399431228638
        p_l.append(p)
        p.start()
    for p in p_l:
        p.join()

    print(time.time()-start)
from threading import Thread
from multiprocessing import Process
import time
#IO密集型
def work():
    time.sleep(2)

if __name__ == '__main__':
    p_l=[]
    start=time.time()
    for i in range(400):
        # p=Process(target=work) #12.104692220687866
        p=Thread(target=work) #2.038116455078125
        p_l.append(p)
        p.start()
    for p in p_l:
        p.join()

 

相关文章:

  • 2021-09-27
  • 2022-02-09
  • 2021-10-28
  • 2021-11-08
  • 2021-06-27
  • 2021-07-03
  • 2021-07-20
猜你喜欢
  • 2021-05-24
  • 2021-06-30
  • 2021-04-21
  • 2021-08-02
  • 2021-12-23
  • 2021-12-10
  • 2022-02-10
相关资源
相似解决方案