当前位置:   article > 正文

python 多进程加速for循环示例,包括如何传参。_python多进程for循环

python多进程for循环
  1. # SuperFastPython.com
  2. # execute tasks in parallel in a for loop
  3. from time import sleep
  4. from random import random
  5. from multiprocessing import Process
  6. # execute a task
  7. def task(arg, i, string_):
  8. print("arg=" + str(arg) + " i=" + str(i) + "string_" + string_)
  9. # generate a random value between 0 and 1
  10. value = random()
  11. # block for a fraction of a second
  12. sleep(value + arg[0])
  13. print(sum(arg))
  14. # report a message
  15. print(f'.done {arg[0]}, generated {value}', flush=True)
  16. # protect the entry point
  17. if __name__ == '__main__':
  18. pool_num = 3
  19. args_list = [[1,2,3,4], [5,6,7,8], [9,10,11,12]]
  20. string_ = "res"
  21. processes = [Process(target=task, args=(args_list[i], i, string_)) for i in range(pool_num)]
  22. # start all processes
  23. for process in processes:
  24. process.start()
  25. # wait for all processes to complete
  26. for process in processes:
  27. process.join()
  28. # report that all tasks are completed
  29. print('Done', flush=True)

过程就是定义几个Process,每个Process执行不同的task。task的区别在于for循环中不同的索引。另外各个Process如果输出文件,那么应写到不同的文件里避免不必要的麻烦。

args_list的由来:对于for循环而言,可以将整个长度进行切分成如上的args_list,再对各个Process传递不同的index值即可。如下所示:

  1. split_size = int(len(accx_cuts) / pool_num)
  2. print("allocate indexes")
  3. args_list = []
  4. for i in range(pool_num):
  5. data_list = [i * split_size + k for k in range(split_size)]
  6. print(i, data_list[0:5], data_list[-5:])
  7. args_list.append(data_list)
  8. processes = [Process(target=task, args=(args_list[i], i, accx_cuts, accy_cuts, accz_cuts)) for i in range(pool_num)]

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/盐析白兔/article/detail/74832
推荐阅读
相关标签
  

闽ICP备14008679号