提高for循环效能---并行处理使用concurrent.futures.Executor.map()传递多个参数

concurrent.futures是Python标准库中的一个模块,提供了高级的并行处理接口。它可以通过线程池或进程池来实现并行处理,简化了并行编程的复杂性。

偏函数(Partial Function)是Python中的一个概念,它通过固定一个或多个函数的参数,从而生成一个新的函数。可以使用functools模块的partial函数来创建一个偏函数,然后将偏函数作为参数传递给Executor.map()方法。

首先使用concurrent.futures.ThreadPoolExecutor创建一个线程池,然后使用偏函数传递多个参数给Executor.map()方法:

from concurrent.futures import ThreadPoolExecutor
from functools import partial

def summary_table(self, request):
   parentDepartList = [1,2,3,4,5]
   org_ids_list = []
   for depart in parentDepartList:
       data_list2 = [org_idDict, depart]
       with ThreadPoolExecutor(max_workers=6) as executor:
           process_data_partial = partial(self.loop_process, data2=data_list2)
           result = executor.map(process_data_partial, org_idDict[depart])
           for res in result:
               org_ids_list.append(res)
   return JsonResponse({
       'data': org_ids_list
   })

def loop_process(self, org_id, data2):
   # 数据分析处理
   # ……
   return time_cycles_dict

使用functools模块的partial函数创建了一个偏函数process_data_partial,并将data_list2作为参数固定在偏函数中。在Executor.map()方法中,只传递了org_idDict[depart](此处是需要被循环的参数)作为参数,而process_data_partial会自动带上固定的data_list2参数,同时传递的多个参数都可以放在data_list2中传递给被调用的函数。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值