Python编程:基于multiprocessing的Pool的并行计算

【Python】Python进程池multiprocessing.Pool八个函数对比:apply、apply_async、map、map_async、imap、starmap... map 和 map_async 可以并发执行任务。apply 和 apply_async 一次只能执行一个任务,但 apply_async 可以异步执行,因而也可以实现并发。 一、单次执行 1、单次同步执行 一个任务执行完再进行下一个任务 import multiprocessing import time def func(msg): print("msg:", msg) time.sleep(2) print("end") if __name__ == "__m 阅读详情

前言

之前做机器视觉任务处理图片时会遇到耗时较长的情况,当时就想着如果使用多进程应该能有提升。于是这里先做一个代码框架的记录,以后需要时再用上。

方法

原有的代码:

import tqdm,glob
def process_img(fname:str):
    try:
        # do something
        i=1
        return True,""
    except Exception as e:
        return False,str(e)

if __name__ == '__main__':
    pbar = tqdm(total=1400)
    for fname in glob.iglob("./imgs/*.jpg",recursive=True):
        pbar.update()
        succ,msg = process_img(fname)
        if not succ:
            print(msg)
    pbar.close()

为了方便改写,我们使用map重构:

import tqdm,glob
def process_img(fname:str):
    try:
        # do something
        i=1
        return True,""
    except Exception as e:
        return False,str(e)

if __name__ == '__main__':
    pbar = tqdm(total=1400)
    for succ,msg in map(process_img,glob.iglob("./imgs/*.jpg",recursive=True)):
        pbar.update()
        if not succ:
            print(msg)
    pbar.close()

然后我们基于multiprocessing改写为并行方式,步骤如下;

  1. 定义进程池
  2. 定义并行处理函数
  3. 使用Pool.map或者imap替代内置的map函数

代码如下:

import tqdm,glob
def process_img(fname:str):
    try:
        # do something
        i=1
        return True,""
    except Exception as e:
        return False,str(e)

if __name__ == '__main__':
    from multiprocessing import Pool
    with Pool(processes=None) as p: # 进程池,缺省值为CPU核心数
        pbar = tqdm(total=1400)
        for succ,msg in p.map(
            process_img,                                # 并行计算函数
            glob.iglob("./imgs/*.jpg",recursive=True),  # 可迭代对象
            20                                          # chunk数?
            ):
            pbar.update()
            if not succ:
                print(msg)
        pbar.close()

关于p.map的的chunksize参数,官方文档是这么写的:

This method chops the iterable into a number of chunks which it submits to the process pool as separate tasks. The (approximate) size of these chunks can be specified by setting chunksize to a positive integer.

应该也可以不设置?以后实践了再试试

本文参考: 实用模块-9-多任务之蚂蚁搬家:multiprocessing模块_哔哩哔哩_bilibili

Python multiprocessing模块Pool类介绍 multiprocessing.Pool 类是 Python 中用于并行处理任务的强大工具,它可以创建一个进程池,允许你在多个进程中并行执行任务,从而充分利用多核 CPU 的性能。 阅读详情

相关推荐

python-multiprocessing 多进程并行计算

#16.6.1.1. The Process class from multiprocessing import Process import os import time start_time = time.time() def info(title): print(title) if hasattr(os, 'getppid'): # only available on

自由 平等~忠诚 奉献 1万+

Python 多进程 multiprocessing.Pool类详解

如果操作的对象数目不大时,还可以直接使用Process类动态的生成多个进程,十几个还好,但是如果上百个甚至更多,那手动去限制进程数量就显得特别的繁琐,此时进程池就派上用场了。程序中的r1表示全部进程执行结束后全局的返回结果集,run函数有返回值,所以一个进程对应一个返回结果,这个结果存在一个列表中,也就是一个结果堆中,实际上是用了队列的原理,等待所有进程都执行完毕,就返回这个列表(列表的顺序不定)。如果池满,请求就会告知先等待,直到池中有进程结束,才会创建新的进程来执行这些请求。

biggolden1的博客 5475

Python 多进程 multiprocessing Pool 坑

环境:win 7+spyder2.38+py3.5 这几天在写个使用 multiprocessing 调用 Pool 进程池的程序,原本使用函数的方式,一切正常。后来改成了 class的方式,就一直出问题,排查后发现如果在类中 使用了 自己定义的 import 的包中的类/函数/方法,然后多进程调用的方法中如果使用了这些,就会导致cpu高占用,但是程序并没有报错,最后测试使用如下的程序是可以

seanb的博客 2万+

python测试开发基础---multiprocessing.Pool

进程池是一个包含多个工作进程的池子,用来处理多个任务。你可以将任务分配给池中的进程,池会自动管理这些进程。模块允许你使用多个进程并行执行任务,这可以提高程序的性能,尤其是在需要大量计算的情况下。类是一个常用工具,可以帮助你更轻松地管理多个进程。

小白的学习日志 1753

Python多进程编程:利用multiprocessing模块实现并行计算

每个进程拥有独立的内存空间,进程间的数据共享需要通过进程间通信(IPC)机制实现。与多线程编程相比,多进程编程在CPU密集型任务上更具优势,因为每个进程可以独立地运行在一个处理器核心上,避免了全局解释器锁(GIL)的限制。多进程编程是一种重要的并行处理机制,它可以充分利用多核处理器的计算能力,提高程序的执行效率。在实际应用中,我们可以根据任务的性质和需求选择合适的并行处理机制,如多进程、多线程或协程等。通过本文的介绍,我们了解了Python多进程编程的概念和原理,以及如何使用。),然后返回计算结果。

weixin_71166183的博客 820

Python-multiprocessing.Pool异步线程池

''' 当需要创建的子进程数量不多的时候可以直接利用multiprocessing中的Process动态生成多个进程 但是,如果是成百上千个任务,手动创建显然不合适,此时就可以用multiprocessing下的Pool类完成 初始化Pool时,可以指定一个最大的进程数,当有新的请求提交到Pool中时,如果池子还没有满, (即对进程进行有效的管理)那么会创建一个新的进程来执行该请求,如果进程数达...

zbrj12345的博客 2171

Python multiprocessing进程池使用详解

python multiprocessing应用介绍及常见问题分析

weixin_39253570的博客 2588

Python-multiprocessing.Pool同步线程池

'' 当需要创建的子进程数量不多的时候可以直接利用multiprocessing中的Process动态生成多个进程 但是,如果是成百上千个任务,手动创建显然不合适,此时就可以用multiprocessing下的Pool类完成 初始化Pool时,可以指定一个最大的进程数,当有新的请求提交到Pool中时,如果池子还没有满, (即对进程进行有效的管理)那么会创建一个新的进程来执行该请求,如果进程数达到...

zbrj12345的博客 2645

【python】详解multiprocessing多进程-Pool进程池模块(二)

       Multiprocessing.Pool可以提供指定数量的进程供用户调用,当有新的请求提交到pool中时,如果池还没有满,那么就会创建一个新的进程用来执行该请求;但如果池中的进程数已经达到规定最大值,那么该请求就会等待,直到池中有进程

brucewong0516的博客 8万+

GitLab中国区注册终极解决方案:绕过+86手机验证的实战技巧(2023最新)

本文详细解析了GitLab中国区注册时绕过+86手机验证的三种实战技巧,包括开发者工具调试方案、使用国际号码的变通方案以及本地化部署替代方案。通过技术分析和实践验证,帮助开发者顺利注册GitLab账号,提升团队协作效率。

rl6adventurer的博客 1518

从理论到实践:全面解析Cmk(设备能力指数)的应用与优化

本文全面解析了设备能力指数Cmk的核心概念、计算逻辑与关键应用场景。Cmk作为衡量设备本身固有加工能力的黄金标准,在设备验收、大修后验证及过程能力根因分析中至关重要。文章通过实战案例,详细阐述了执行Cmk测试的“五大固定”黄金法则、数据计算分析方法,并提供了Cmk不达标时的系统性排查与优化策略,帮助制造企业实现预防性质量管理。

jump7的博客 551

一文搞明白Python多进程编程:multiprocessing库

本文试图讲清楚Python多进程编程

闵行小鱼塘 6124

52、Power BI Desktop 数据筛选全攻略

本文全面介绍了Power BI Desktop中各类数据筛选功能的使用方法,涵盖布尔型数据筛选、高级文本筛选、Top N筛选、可视化级别、页面级别和报告级别筛选等核心操作。通过详细步骤、流程图和实际案例,帮助用户深入理解筛选器的层级关系与综合应用技巧,并提供常见问题解决方案,助力高效精准的数据分析与可视化展示。

linux6sysadmin的博客 111

【Python】multiprocessing 模块:多进程并行计算

Python的multiprocessing模块用于多进程并行计算,可以充分利用多核CPU进行任务加速,突破PythonGIL(全局解释器锁)的限制,提高程序执行效率。multiprocessing.Process创建进程以实现并行计算。Pool.map()批量处理任务,更高效。Queue、Manager进行进程间通信。Lock同步进程,防止竞争。适用于CPU密集型任务,如科学计算、数据处理、机器学习等。

彬彬侠的博客 2588

190、LLC谐振变换器的样机调试实战(问题定位)

这篇实战笔记总结了LLC谐振变换器样机调试中的五大典型问题及解决方案:1)空载炸机源于谐振电容纹波电流能力不足;2)轻载啸叫因控制环路不稳定,需调整突发模式阈值;3)MOSFET过热由死区时间不当导致,需精确优化实现ZVS;4)输出纹波大由PCB布局耦合引起,需优化共模抑制;5)启动过冲需延长软启动时间。作者强调调试需结合示波器、热成像仪等工具,理论计算与实测并重,并详细记录每次参数调整。文章指出LLC调试是不断试错的过程,关键是通过现象分析本质原因。

Jack010169的博客 58

AI大模型:(三)3.2 Spring AI实现Agent

SpringAI实现了流式对话功能,通过与Ollama模型集成完成前后端交互,当前版本存在thinking信息丢失问题。系统支持两种工具注册方式(方法注解和函数式),并内置时间工具类展示外部工具调用能力。记忆功能提供多种存储方案(内存、JDBC、NoSQL等),实现跨对话轮次的上下文保持。MCP协议集成方面,服务端实现计算和业务查询工具,客户端支持12306及自定义业务系统接入。完整演示了流式对话、工具调用与记忆功能的综合应用。该实践构建了具备复杂交互能力的AI系统,同时指出生产环境需关注的安全与优化问题。

haylee的专栏 1027

python进阶之进程池multiprocessing.Pool

python的进程池multiprocessing.Pool有八个重要函数: apply、apply_async、map、map_async、imap、imap_unordered、starmap、starmap_async 下面是他们的各个比较和区别: 1)apply 和 apply_async:apply 一次执行一个任务,但 apply_async 可以异步执行,因而也可以实现并发 我们使用代码实现下: apply: (一个任务执行完再进行下一个任务) def func(msg): print

陆撄宁的博客 1万+

YOLOv11 热力图可视化全流程:从模型解释到科研论证,让检测结果“有理可看”

无论是科研中需要严谨的模型解释,还是工业里要高效的缺陷定位,这套方法都能让你在“模型黑箱”与“业务需求”之间架起一座可视化的桥梁。别再让模型决策“无据可依”——现在就动手生成你的第一幅热力图,让 YOLOv11 的每一次检测都“有理可看”,用可视化的力量推动你的 AI 研究与落地走向深入!某团队在论文中通过热力图对比,证明其改进的注意力模块可使模型对小目标的关注区域更精准,实验论证说服力提升 50%;工业质检场景下,热力图帮助工程师快速定位模型漏检缺陷的原因——原来是对某类缺陷的特征关注不足。

m0_71589036的博客 682

【Python】【并行计算】Python 多核并行计算

  原文转自:https://abcdabcd987.com/python-multiprocessing/     Python 多核并行计算 Nov 2, 2016 • python 以前写点小程序其实根本不在乎并行,单核跑跑也没什么问题,而且我的电脑也只有双核四个超线程(下面就统称核好了),觉得去折腾并行没啥意义(除非在做IO密集型任务)。然后自从用上了32核128GB内存,看到...

qq_24920947的博客 8538

华为OD机试 - 机器人活动区域(Java 双机位C卷 200分)

现有一个机器人,可放置于 M × N的网格中任意位置,每个网格包含一个非负整数编号。之后M行表示网格数值,每行N个数值(数值大小用k表示),数值间用单个空格分隔,行首行尾无多余空格。说明:图中绿色区域,相邻网格差值绝对值都小于等于1,且为最大区域,对应网格点数目为6。M、N、k均为整数,且1

学Java,找哪吒 917

蓝牙模块HM-10手册

蓝牙模块HM-10手册,该手册对蓝牙模块HM-10进行了详细的介绍和使用方法以及一些AT指令。

python的multiprocessing的pool.map函数使用方法

顺便记录一下: import numpy as np from time import time from multiprocessing import Process, Queue import multiprocessing as mp import random def my_func(x): s0 = time() res = 0 for _ in range...

your_answer的博客 1万+

Statistics and Machine Learning Toolbox

Statistics and Machine Learning Toolbox(带书签),MATLAB统计学习工具

Python进程池multiprocessing.Pool的用法

一、multiprocessing模块 multiprocessing模块提供了一个Process类来代表一个进程对象,multiprocessing模块像线程一样管理进程,这个是multiprocessing的核心,它与threading很相似,对多核CPU的利用率会比threading好的多 看一下Process类的构造方法: __init__(self, group=None, target=None, name=None, args=(), kwargs={}) 参数说明: group:进程所属组

Asaasa1的博客 6928

怀旧版电脑GBC模拟器

再现原版GBC掌机的界面,电脑运行连游戏界面都一样大小,很怀旧,很真实,(英文版)强烈推荐,很小的文件,很难才找到的。

深度学习工具包 DeepLearningToolbox

深度学习工具包Deprecation notice.-----This toolbox is outdated and no longer maintained.There are much better tools available for deep learning than this toolbox, e.g. [Theano](http://deeplearning.net/software/theano/), [torch](http://torch.ch/) or [tensorflow](http://www.tensorflow.org/)I would suggest you use one of the tools mentioned above rather than use this toolbox.Best, Rasmus.DeepLearnToolbox================A Matlab toolbox for Deep Learning.Deep Learning is a new subfield of machine learning that focuses on learning deep hierarchical models of data.It is inspired by the human brain's apparent deep (layered, hierarchical) architecture.A good overview of the theory of Deep Learning theory is[Learning Deep Architectures for AI](http://www.iro.umontreal.ca/~bengioy/papers/ftml_book.pdf)For a more informal introduction, see the following videos by Geoffrey Hinton and Andrew Ng.* [The Next Generation of Neural Networks](http://www.youtube.com/watch?v=AyzOUbkUf3M) (Hinton, 2007)* [Recent Developments in Deep Learning](http://www.youtube.com/watch?v=VdIURAu1-aU) (Hinton, 2010)* [Unsupervised Feature Learning and Deep Learning](http://www.youtube.com/watch?v=ZmNOAtZIgIk) (Ng, 2011)If you use this toolbox in your research please cite [Prediction as a candidate for learning deep hierarchical models of data](http://www2.imm.dtu.dk/pubdb/views/publication_details.php?id=6284)```@MASTERSTHESIS\{IMM2012-06284, author = "R. B. Palm", title = "Prediction as a candidate for learning deep hierarchical models of data", year = "2012",}```Contact: rasmusbergpalm at gmail dot comDirectories included in the toolbox-----------------------------------`NN/` - A library for Feedforward Backpropagation Neural Networks`CNN/` - A library for Convolutional Neural Networks`DBN/` - A library for Deep Belief Networks`SAE/` - A library for Stacked Auto-Encoders`CAE/` - A library for Convolutional Auto-Encoders`util/` - Utility functions used by the libraries`data/` - Data used by the examples`tests/` - unit tests to verify toolbox is workingFor references on each library check REFS.mdSetup-----1. Download.2. addpath(genpath('DeepLearnToolbox'));Example: Deep Belief Network---------------------```matlabfunction test_example_DBNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit RBM and visualize its weightsrand('state',0)dbn.sizes = [100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);figure; visualize(dbn.rbm{1}.W'); % Visualize the RBM weights%% ex2 train a 100-100 hidden unit DBN and use its weights to initialize a NNrand('state',0)%train dbndbn.sizes = [100 100];opts.numepochs = 1;opts.batchsize = 100;opts.momentum = 0;opts.alpha = 1;dbn = dbnsetup(dbn, train_x, opts);dbn = dbntrain(dbn, train_x, opts);%unfold dbn to nnnn = dbnunfoldtonn(dbn, 10);nn.activation_function = 'sigm';%train nnopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.10, 'Too big error');```Example: Stacked Auto-Encoders---------------------```matlabfunction test_example_SAEload mnist_uint8;train_x = double(train_x)/255;test_x = double(test_x)/255;train_y = double(train_y);test_y = double(test_y);%% ex1 train a 100 hidden unit SDAE and use it to initialize a FFNN% Setup and train a stacked denoising autoencoder (SDAE)rand('state',0)sae = saesetup([784 100]);sae.ae{1}.activation_function = 'sigm';sae.ae{1}.learningRate = 1;sae.ae{1}.inputZeroMaskedFraction = 0.5;opts.numepochs = 1;opts.batchsize = 100;sae = saetrain(sae, train_x, opts);visualize(sae.ae{1}.W{1}(:,2:end)')% Use the SDAE to initialize a FFNNnn = nnsetup([784 100 10]);nn.activation_function = 'sigm';nn.learningRate = 1;nn.W{1} = sae.ae{1}.W{1};% Train the FFNNopts.numepochs = 1;opts.batchsize = 100;nn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.16, 'Too big error');```Example: Convolutional Neural Nets---------------------```matlabfunction test_example_CNNload mnist_uint8;train_x = double(reshape(train_x',28,28,60000))/255;test_x = double(reshape(test_x',28,28,10000))/255;train_y = double(train_y');test_y = double(test_y');%% ex1 Train a 6c-2s-12c-2s Convolutional neural network %will run 1 epoch in about 200 second and get around 11% error. %With 100 epochs you'll get around 1.2% errorrand('state',0)cnn.layers = { struct('type', 'i') %input layer struct('type', 'c', 'outputmaps', 6, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %sub sampling layer struct('type', 'c', 'outputmaps', 12, 'kernelsize', 5) %convolution layer struct('type', 's', 'scale', 2) %subsampling layer};cnn = cnnsetup(cnn, train_x, train_y);opts.alpha = 1;opts.batchsize = 50;opts.numepochs = 1;cnn = cnntrain(cnn, train_x, train_y, opts);[er, bad] = cnntest(cnn, test_x, test_y);%plot mean squared errorfigure; plot(cnn.rL);assert(er<0.12, 'Too big error');```Example: Neural Networks---------------------```matlabfunction test_example_NNload mnist_uint8;train_x = double(train_x) / 255;test_x = double(test_x) / 255;train_y = double(train_y);test_y = double(test_y);% normalize[train_x, mu, sigma] = zscore(train_x);test_x = normalize(test_x, mu, sigma);%% ex1 vanilla neural netrand('state',0)nn = nnsetup([784 100 10]);opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samples[nn, L] = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.08, 'Too big error');%% ex2 neural net with L2 weight decayrand('state',0)nn = nnsetup([784 100 10]);nn.weightPenaltyL2 = 1e-4; % L2 weight decayopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex3 neural net with dropoutrand('state',0)nn = nnsetup([784 100 10]);nn.dropoutFraction = 0.5; % Dropout fraction opts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex4 neural net with sigmoid activation functionrand('state',0)nn = nnsetup([784 100 10]);nn.activation_function = 'sigm'; % Sigmoid activation functionnn.learningRate = 1; % Sigm require a lower learning rateopts.numepochs = 1; % Number of full sweeps through dataopts.batchsize = 100; % Take a mean gradient step over this many samplesnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex5 plotting functionalityrand('state',0)nn = nnsetup([784 20 10]);opts.numepochs = 5; % Number of full sweeps through datann.output = 'softmax'; % use softmax outputopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, train_x, train_y, opts);[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');%% ex6 neural net with sigmoid activation and plotting of validation and training error% split training data into training and validation datavx = train_x(1:10000,:);tx = train_x(10001:end,:);vy = train_y(1:10000,:);ty = train_y(10001:end,:);rand('state',0)nn = nnsetup([784 20 10]); nn.output = 'softmax'; % use softmax outputopts.numepochs = 5; % Number of full sweeps through dataopts.batchsize = 1000; % Take a mean gradient step over this many samplesopts.plot = 1; % enable plottingnn = nntrain(nn, tx, ty, opts, vx, vy); % nntrain takes validation set as last two arguments (optionally)[er, bad] = nntest(nn, test_x, test_y);assert(er < 0.1, 'Too big error');```[![Bitdeli Badge](https://d2weczhvl823v0.cloudfront.net/rasmusbergpalm/deeplearntoolbox/trend.png)](https://bitdeli.com/free "Bitdeli Badge")

python 并行计算 multiprocessing、multiprocess模块 简介

目录 多进程才是真·并行 multiprocessing模块 1、创建子进程 2、进程间通信——数据共享 3、进程间通信——数据传递 4、锁(同步原语) 5、其他重要函数 multiprocess模块 实例(multiprocessing模块) (1)multiprocessing.Process() (2)multiprocessing.Pool(),apply方法 (3)multiprocessing.Pool(),apply_async方法 (4)multiprocessin

whatday的专栏 5005

Python multiprocessing Pool map()实例

原因:并行处理某个目录下文件中的字符个数和行数,存入res.txt文件中 # coding=utf-8 import os import time import logging from multiprocessing import Pool x1, x2 = 3, 7 logging.basicConfig( level=logging.INFO, format="%(asct...

迷心兔的博客 4401
上一篇: PyTorch笔记:修改模型中的某些权重参数
下一篇: ML笔记:sklearn的k近邻与可视化
X-ocean
博客等级 码龄6年 34粉丝 57原创
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

个

红包个数最小为10个

元

红包金额最低5元

当前余额3.43元 前往充值 >
需支付:10.00元
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付元
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值