Python中使用concurrent执行多进程任务
随着计算机技术的发展,诸如GPU和超算平台等越来越发达,这些技术的本质其实并没有带来算法上的革新,之所以能够提升计算的速度和规模,很大程度上是因为分布式和并行计算的优势。这里我们介绍一个简单的python自带的多进程的代码实现,使用的是concurrent这个工具,同时我们也会介绍如何更好的配置多进程的资源。
- concurrent使用示例
concurrent是python自带的一个多进程实现仓库,不需要额外的安装。这里我们先介绍一个没有多进程的示例代码:
# sleep.py import time def sleep(seconds): time.sleep(seconds) if __name__ == '__main__': times = [1] * 10 time0 = time.time() for t in times: sleep(t) time1 = time.time() print ('The time cost is: {}s'.format(time1 - time0)) 这个代码的功能其实就是休眠10s的时间,也比较容易,我们可以看一下这个代码的执行结果:
[dechin@dechin-manjaro concurrent]$ python3 sleep.py The time cost is: 10.014754295349121s 在我们统计时间的时候,发现会比10s的时间多出来一些,这部分时间不仅仅包含这个python程序执行的时间,跟时间的统计方式也有一定的关系,一般我们可以忽略这部分的gap时间。
我们假定上面这个程序中的sleep函数功能不是休眠1s的时间,而是执行一个耗时为1s的计算任务,而我们有很多的cpu,希望能够加速这个计算的过程,这个时候我们就需要用到多进程的技术,下面是修改为多进程之后的代码:
import concurrent.futures import time def sleep(seconds): time.sleep(seconds) if __name__ == '__main__': times = [1] * 10 time0 = time.time() with concurrent.futures.ProcessPoolExecutor() as executor: executor.map(sleep, times) time1 = time.time() print ('The time cost is: {}s'.format(time1 - time0))