在python(2020)中,并行化for循环的最佳方法是什么?

2024-04-30 03:15:03 发布

您现在位置:Python中文网/ 问答频道 /正文

这不是一个重复的问题。我遇到了一个问题。没有找到我的答案。

我想在python中并行化for循环。我所说的并行化是指:

  • 循环的每一次迭代都是独立运行的,不是按顺序运行的(不像整个for循环与主程序分开,而是for循环仍然按顺序运行)

  • 解决方案应该是跨平台的,即在所有平台上工作。就像我尝试joblib时一样,我无法让它在Ubuntu或不在Windows上工作的Ray上工作

家长的问题真的很老了,我在想,现在是否有更好的办法


Tags: 答案for顺序ubuntuwindows跨平台平台解决方案
2条回答

您可以使用Thread对象

from threading import Thread
from time import sleep
from random import randint

def f(i):
    sleep(randint(1, 3))
    print(f'function called from Thread {i}')

for i in range(5):
    Thread(target=f, args=(i,)).start()

和输出

function called from Thread 4
function called from Thread 3
function called from Thread 1
function called from Thread 0
function called from Thread 2

这是2020年最简单的方法 (它独立地运行每个迭代&这在ubuntu和Windows上都有效)

您可以使用asyncio。(可在此处找到文档)。它被用作多个Python异步框架的基础,它提供高性能的网络和Web服务器、数据库连接库、分布式任务队列等。此外,它还具有高级和低级API来适应任何类型的问题。p>

import asyncio

def background(f):
    def wrapped(*args, **kwargs):
        return asyncio.get_event_loop().run_in_executor(None, f, *args, **kwargs)

    return wrapped

@background
def your_function(argument):
    #code

现在,无论何时调用此函数,都将并行运行,而不会将主程序置于等待状态。您也可以使用它来并行化for循环。当调用for循环时,虽然循环是顺序的,但每次迭代都会在解释器到达主程序时与主程序并行运行。例如:

@background
def your_function(argument):
    time.sleep(5)
    print('function finished for '+str(argument))


for i in range(10):
    your_function(i)


print('loop finished')

这将产生以下输出:

loop finished
function finished for 4
function finished for 8
function finished for 0
function finished for 3
function finished for 6
function finished for 2
function finished for 5
function finished for 7
function finished for 9
function finished for 1

相关问题 更多 >