|
| 1 | +#-*- coding:utf8 -*- |
| 2 | +#author : Lenovo |
| 3 | +#date: 2018/10/9 |
| 4 | +#由于Python中GIL锁的限制 python无法利用多核cpu的特点 |
| 5 | +#对于IO操作来说 瓶颈不在于多线程和多进程 多线程比多进程好 因为进程间的切换是需要花费时间的 |
| 6 | +import time |
| 7 | +from concurrent.futures import ThreadPoolExecutor,as_completed |
| 8 | +from concurrent.futures import ProcessPoolExecutor |
| 9 | + |
| 10 | +# #1.耗费cpu的操作 比如图像处理 以及机器学习的算法 比特币挖矿 此时多进程优于多线程 |
| 11 | +# #斐波那契数列 |
| 12 | +# def fib(n): |
| 13 | +# if n<=2: return 1 |
| 14 | +# return fib(n-1)+fib(n-2) |
| 15 | +# |
| 16 | +# if __name__=='__main__': |
| 17 | +# #在这里更改ProcessPoolExecutor或者ThreadPoolExecutor就可以切换多进程和多线程 要注意的是多进程需要使用if __name__=='__main__': |
| 18 | +# #对斐波那契数列数列的25-40项进行测试 多线程 102秒 多进程 20秒 实在是可怕。。。 |
| 19 | +# with ProcessPoolExecutor(3) as excutor: #在这里可以设置开启几个线程或几个进程 |
| 20 | +# all_task=[excutor.submit(fib,(num)) for num in range(25,40)] |
| 21 | +# start_time=time.time() |
| 22 | +# for future in as_completed(all_task): |
| 23 | +# data=future.result() #可以返回程序执行完成的结果 |
| 24 | +# print('result:{}'.format(data)) |
| 25 | +# print('time is {}'.format(time.time()-start_time)) |
| 26 | + |
| 27 | +#----------------------------------------------------------------------------------------------------------- |
| 28 | +#对于IO操作来说 多线程优于多进程 |
| 29 | +def random(n): |
| 30 | + time.sleep(n) #用sleep模拟输入输出 |
| 31 | + return n |
| 32 | + |
| 33 | +if __name__=='__main__': |
| 34 | + #在这里更改ProcessPoolExecutor或者ThreadPoolExecutor就可以切换多进程和多线程 要注意的是多进程需要使用if __name__=='__main__': |
| 35 | + #对斐波那契数列数列的25-40项进行测试 多线程 102秒 多进程 20秒 实在是可怕。。。 |
| 36 | + with ProcessPoolExecutor(3) as excutor: #在这里可以设置开启几个线程或几个进程 |
| 37 | + all_task=[excutor.submit(random,(num)) for num in range(25,40)] |
| 38 | + start_time=time.time() |
| 39 | + for future in as_completed(all_task): |
| 40 | + data=future.result() #可以返回程序执行完成的结果 |
| 41 | + print('result:{}'.format(data)) |
| 42 | + print('time is {}'.format(time.time()-start_time)) |
| 43 | + |
0 commit comments