PythonStudy——多线程与多进程 对比

IO密集型任务 子进程解决方案

# test1 IO密集型任务 (法1:开启子进程的解决)
from multiprocessing import Process
import time

def task():
    time.sleep(2)

if __name__ == '__main__':
    start = time.time()
    lst = []
    # 用于开启100个子进程
    for i in range(100):
        p = Process(target=task)
        p.start()
        # 将p子进程对象存入列表中,此时列表作为一个容器接受所有实例化出来的对象
        lst.append(p)
    for p in lst:
        p.join()
    end = time.time()
    print(end-start)  

# 耗时 2.1534228324890137

 IO密集型任务任务 子线程解决方案

from threading import Thread
import time

def task():
    time.sleep(2)

if __name__ == '__main__':
    start = time.time()
    lst = []
    # 用于开启100个子进程
    for i in range(100):
        p = Thread(target=task)
        p.start()
        # 将p子进程对象存入列表中,此时列表作为一个容器接受所有实例化出来的对象
        lst.append(p)
    for p in lst:
        p.join()
    end = time.time()
    print(end-start)  # 耗时 2.0103108882904053

猜你喜欢

转载自www.cnblogs.com/tingguoguoyo/p/10980860.html