程序

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
import asyncio
import time


async def async_io(idx: int):
if idx == 1:
await asyncio.sleep(1)
else:
await asyncio.sleep(6 - idx)
print("async_io", idx)
return idx


async def async_test1():
start = time.time()
task1 = asyncio.create_task(async_io(1))
task2 = asyncio.create_task(async_io(2))
task3 = asyncio.create_task(async_io(3))
task4 = asyncio.create_task(async_io(4))
task5 = asyncio.create_task(async_io(5))

idx1 = await task1
print("task1", idx1)
idx2 = await task2
print("task2", idx2)
idx3 = await task3
print("task3", idx3)
idx4 = await task4
print("task4", idx4)
idx5 = await task5
print("task5", idx5)

print("time -> ", time.time() - start)
return {"msg": "test_async"}


async def async_test2():
start = time.time()

idx1 = await async_io(1)
print("task1", idx1)
idx2 = await async_io(2)
print("task2", idx2)
idx3 = await async_io(3)
print("task3", idx3)
idx4 = await async_io(4)
print("task4", idx4)
idx5 = await async_io(5)
print("task5", idx5)

print("time -> ", time.time() - start)
return {"msg": "test_async"}


if __name__ == "__main__":
asyncio.run(async_test1())
print("========")
asyncio.run(async_test2())

运行结果

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
async_io 1
async_io 5
task1 1
async_io 4
async_io 3
async_io 2
task2 2
task3 3
task4 4
task5 5
time -> 4.000199794769287
========
async_io 1
task1 1
async_io 2
task2 2
async_io 3
task3 3
async_io 4
task4 4
async_io 5
task5 5
time -> 11.003704071044922