欢迎来到代码驿站!

Python代码

当前位置:首页 > 软件编程 > Python代码

Python多线程多进程实例对比解析

时间:2020-10-15 23:15:34|栏目:Python代码|点击:

多线程适合于多io操作

多进程适合于耗cpu(计算)的操作

# 多进程编程
# 耗cpu的操作,用多进程编程, 对于io操作来说,使用多线程编程
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from concurrent.futures import ProcessPoolExecutor


def fib(n):
  if n <= 2:
    return 1
  return fib(n - 2) + fib(n - 1)

if __name__ == '__main__':

  # 1. 对于耗cpu操作,多进程优于多线程

  # with ThreadPoolExecutor(3) as executor:
  #   all_task = [executor.submit(fib, num) for num in range(25, 35)]
  #   start_time = time.time()
  #   for future in as_completed(all_task):
  #     data = future.result()
  #     print(data)
  #   print("last time :{}".format(time.time() - start_time)) # 3.905290126800537

  # 多进程 ,在window环境 下必须放在main方法中执行,否则抛异常
  with ProcessPoolExecutor(3) as executor:
    all_task = [executor.submit(fib, num) for num in range(25, 35)]
    start_time = time.time()
    for future in as_completed(all_task):
      data = future.result()
      print(data)
    print("last time :{}".format(time.time() - start_time)) # 2.6130592823028564

可以看到在耗cpu的应用中,多进程明显优于多线程 2.6130592823028564 < 3.905290126800537

下面模拟一个io操作

# 多进程编程
# 耗cpu的操作,用多进程编程, 对于io操作来说,使用多线程编程
import time
from concurrent.futures import ThreadPoolExecutor, as_completed
from concurrent.futures import ProcessPoolExecutor

def io_operation(n):
  time.sleep(2)
  return n


if __name__ == '__main__':

  # 1. 对于耗cpu操作,多进程优于多线程

  # with ThreadPoolExecutor(3) as executor:
  #   all_task = [executor.submit(io_operation, num) for num in range(25, 35)]
  #   start_time = time.time()
  #   for future in as_completed(all_task):
  #     data = future.result()
  #     print(data)
  #   print("last time :{}".format(time.time() - start_time)) # 8.00358772277832



  # 多进程 ,在window环境 下必须放在main方法中执行,否则抛异常
  with ProcessPoolExecutor(3) as executor:
    all_task = [executor.submit(io_operation, num) for num in range(25, 35)]
    start_time = time.time()
    for future in as_completed(all_task):
      data = future.result()
      print(data)
    print("last time :{}".format(time.time() - start_time)) # 8.12435245513916

可以看到 8.00358772277832 < 8.12435245513916, 即是多线程比多进程更牛逼!

上一篇:Python中使用platform模块获取系统信息的用法教程

栏    目:Python代码

下一篇:python 基于dlib库的人脸检测的实现

本文标题:Python多线程多进程实例对比解析

本文地址:http://www.codeinn.net/misctech/11593.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有