0
点赞
收藏
分享

微信扫一扫

python加速记录

caoxingyu 2022-08-23 阅读 68
python

目录

加速方式记录

Concurrent.futures

# 线程池:

from concurrent.futures import ThreadPoolExecutor
with ThreadPoolExecutor(max_workers=5) as executor:
     executor.map(function, iterable)

# 进程池:

from concurrent.futures import ProcessPoolExecutor
with ProcessPoolExecutor(max_workers=5) as executor:
     executor.map(function, iterable)

官方参考资料:https://pythonhosted.org/futures/
下面是一个实例

from concurrent.futures import ProcessPoolExecutor
from functools import partial

with ProcessPoolExecutor(max_workers=50) as executor:
    func = partial(
        conf_matrix_per_image,
        num_classes=seg_num_classes,
        cls_mapping=self.CLASSES)
    rets = executor.map(func, preds, gt_files)

相比于Multiprocessing,本质区别并不大,有的也只是调用方式略有差异。先有的 multiprocessing,后有的 concurrent.futures,后者的出现就是为了降低编写代码的难度,后者的学习成本较低。

Multiprocessing

既能多线程,也可以多进程

Multiprocessing 即有线程池,也是进程池,简单的使用方法如下:

# 线程池:

from multiprocessing.dummy import Pool as ThreadPool
with ThreadPool(processes=100) as executor:
    executor.map(func, iterable)
    

# 进程池:

from multiprocessing import Pool as ProcessPool
with ProcessPool(processes=10) as executor:
    executor.map(func, iterable)

下面是个实例,也可以这么写,并且经过我的尝试,这样写更快。

# 也可以直接这么写,
for idx_in_batch in range(batch_size):
    p = Process(target=per_batch_processing, args=(
        batch_fns, 
        idx_in_batch, 
    ))
    p.start()
    processing.append(p)

    # all over
    for process in processing:
        process.join()

进程、线程与协程的比较

https://blog.csdn.net/Blateyang/article/details/78088851

协程介绍-廖雪峰

https://www.liaoxuefeng.com/wiki/1016959663602400/1017968846697824

多进程和多线程,应该选择哪个?

对于IO密集型任务:

单进程单线程直接执行用时:10.0333秒
多线程执行用时:4.0156秒
多进程执行用时:5.0182秒
说明多线程适合IO密集型任务。

对于计算密集型任务

单进程单线程直接执行用时:10.0273秒
多线程执行用时:13.247秒
多进程执行用时:6.8377秒
https://blog.csdn.net/guyue35/article/details/92383687

并行化panoptic seg之后,输出空的json文件

for ...
    for ..
        write json
        write txt

因为并行的时候不容易写入同一个 json (当然也可以使用apply_async,但是只能写入同一个json)
https://blog.csdn.net/qq_45383393/article/details/106154967

  • 两个不相干的函数并行计算
    https://pythontechworld.com/article/detail/Ppj1ndikfYes
  • 多进程有序读取
    https://zhuanlan.zhihu.com/p/43781381

多进程读入到同一个字典里

  • 使用共享对象
    https://stackoverflow.com/questions/28947581/how-to-convert-a-dictproxy-object-into-json-serializable-dict
  • 优化方法
    使用共享对象是执行多进程的不好方法, 更好的方法是收集每次调用的结果

多进程控制使用的cpu数目

https://donggeitnote.com/2020/07/20/python-multiprocessing/

多线程批量处理图像

举报

相关推荐

0 条评论