python线程和进程编程对比

Posted 愤怒中的小草

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python线程和进程编程对比相关的知识,希望对你有一定的参考价值。

import time
from concurrent.futures import ThreadPoolExecutor,as_completed
from concurrent.futures import ProcessPoolExecutor
#多进程编程
#耗CPU的操作,用多进程编程;对于IO操作,使用多线程编程;进程切换的代价要高于线程

#1. 对于耗CPU的操作,多进程优于多线程,比如计算和图形操作 机器学习
def fib(n):
if n<=2:
return 1;
return fib(n-1) + fib(n-2)
"""
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("exe result:{}".format(data))

print("last time is:{}".format(time.time() - start_time))
"""
#window下编程 ProcessPoolExecutor要在main下面,linux下无此问题
#线程花费的时间 明显比进程要多
"""
if __name__ == "__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("exe result:{}".format(data))

print("last time is:{}".format(time.time() - start_time))
"""
#2. 对于IO操作,多线程优于多进程
def random_sleep(n):
time.sleep(n)
return n

if __name__ == "__main__":
#with ThreadPoolExecutor(3) as executor:
with ProcessPoolExecutor(3) as executor:
all_task = [executor.submit(random_sleep,(num)) for num in [2]*30]
start_time = time.time()
for future in as_completed(all_task):
data = future.result()
print("exe result:{}".format(data))

print("last time is:{}".format(time.time() - start_time))






































以上是关于python线程和进程编程对比的主要内容,如果未能解决你的问题,请参考以下文章

python 复习—并发编程实战——线程多进程多协程加速程序运行实例(多线程和多进程的对比)

Python并发编程04/多线程

011_Python中单线程多线程和多进程的效率对比实验

Python 多线程 和 多进程的CPU使用情况进行对比

python对比线程,进程,携程,异步,哪个快

Python的多线程和多进程模块对比测试