【问题标题】:Can I use async/await to accelerate init classes?我可以使用 async/await 来加速初始化类吗?
【发布时间】:2020-04-21 13:40:03
【问题描述】:

我是python初学者,正在尝试编写一些数据分析程序。程序如下:

import asyncio
import time


class Test:
    def __init__(self, task):
        self.task = task
        time.sleep(5)  # here's some other jobs...
        print(f'{self.task = }')


async def main():
    result = []
    tasks = ['task1', 'task2', 'task3', 'task4', 'task5', 'task6', 'task7', 'task8', 'task9']
    print(f"started at {time.strftime('%X')}")

    # I have a program structure like this, can I use async?
    # how to start init tasks at almost the same time?
    for task in tasks:
        result.append(Test(task))
    print(f"finished at {time.strftime('%X')}")


asyncio.run(main())

我尝试了其他一些方法,比如多处理,它可以工作,代码如下:

...
def main():
    result = []
    tasks = ['task1', 'task2', 'task3', 'task4', 'task5', 'task6', 'task7', 'task8', 'task9']
    print(f"started at {time.strftime('%X')}")

    # I have a program structure like this, can I use async?
    # how to start init tasks at the same time?
    p = Pool()
    result = p.map(operation, [(task,) for task in tasks])
    print(f"finished at {time.strftime('%X')}")
...

但我仍然想学习一些“现代方式”来做到这一点。我找到了一个名为“ray”的模块,它是新的。
但是异步可以做到这一点吗?我还在想... 如果有人能给我一些建议,非常感谢。

【问题讨论】:

    标签: python-3.7 python-asyncio


    【解决方案1】:

    您的示例代码不一定会从异步 IO 中受益,因为 __init__ 不是“可等待的”。如果您的代码结构不同并且有适当的瓶颈,您可能会从异步中受益。例如,如果我们有:

    class Task:
        def __init__(self):
            <some not io bound stuff>
            <some io bound task>
    

    我们可以将其重组为:

        class Task:
        def __init__(self):
            <some not io bound stuff>
    
        async def prime(self):
            await <some io bound task>
    

    然后在你的主循环中你可以初始化你正在做的任务,然后在你的事件循环中运行缓慢的prime 步骤。

    我在这里的建议是拒绝这样做,除非你知道你肯定有问题。协程可能非常繁琐,所以只有在需要时才应该这样做!

    【讨论】:

    • 这意味着如果我想使用'async',我需要一些东西来'await',我可以用'async def'设置需要大量时间'awaitable'的工作,对吗?然后? async 可以自动为我完成剩下的工作吗?
    • 大概。它仅适用于慢速任务受 IO 限制的情况。对于 CPU 密集型任务,您可能需要查看多线程
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-10
    • 1970-01-01
    • 2011-10-07
    • 2017-09-30
    • 1970-01-01
    • 1970-01-01
    • 2020-09-17
    相关资源
    最近更新 更多