我是一个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'的模块,是新的。但是async可以做这个吗?我还在想......如果有人能给我一些建议,非常感谢。
你的例子代码不一定能从async IO中受益,因为 __init__
不是 "可等待 "的。如果你的代码结构不同,并且有一个适当的瓶颈,你可能会从async中受益。例如,如果我们有。
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
的步骤。
我的建议是不要这样做,除非你知道你肯定有问题。Coroutines可能会很麻烦,所以你应该只在需要的时候才这样做!我的建议是不要这样做,除非你知道你肯定有问题。