python3 计算密集型和IO密集型进程和线程的区别

# -*- 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

你可能感兴趣的:(python3 计算密集型和IO密集型进程和线程的区别)