直接上代码
import asyncio
import time
async def func(a):
t = await asyncio.sleep(1)
return a+10
async def run():
time_start = time.time()
a_list = [1, 2, 3, 4]
ans_list = await asyncio.gather(*[func(a=a) for a in a_list])
for a, ans in zip(a_list, ans_list):
print(a, ans)
time_end = time.time()
time_spend = time_end - time_start
print('\n{0} cost time {1} s\n'.format(func.__name__, time_spend))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
结果:
import asyncio
import time
def func(a):
time.sleep(1)
return a+10
async def run():
time_start = time.time()
a_list = [1, 2, 3, 4]
ans_list = [func(a=a) for a in a_list]
for a, ans in zip(a_list, ans_list):
print(a, ans)
time_end = time.time()
time_spend = time_end - time_start
print('\n{0} cost time {1} s\n'.format(func.__name__, time_spend))
if __name__ == '__main__':
loop = asyncio.get_event_loop()
loop.run_until_complete(run())
结果:
在协程中要尽量避免使用阻塞的写法。
|