Python async异步编程与同步对比
同步代码
def test1():
for i in range(10):
time.sleep(3)
print(i,"test1")
def test2():
for i in range(15):
time.sleep(2)
print(i,"test2")
start_time=time.time()
test1()
test2()
end_time=time.time()
print(end_time-start_time)
执行结果:
0 test1
1 test1
2 test1
3 test1
4 test1
5 test1
6 test1
7 test1
8 test1
9 test1
0 test2
1 test2
2 test2
3 test2
4 test2
5 test2
6 test2
7 test2
8 test2
9 test2
10 test2
11 test2
12 test2
13 test2
14 test2
60.015082120895386
异步代码:
import asyncio
import time
import threading
async def test1():
for i in range(10):
await asyncio.sleep(3)
print(i,"test1")
async def test2():
for i in range(15):
await asyncio.sleep(2)
print(i,"test2")
loop = asyncio.get_event_loop()
# 1. 将异步函数加入事件队列
tasks = [
test1(),
test2()
]
# 2. 执行事件队列, 直到最晚的一个事件被处理完毕后结束
start_time=time.time()
loop.run_until_complete(asyncio.wait(tasks))
loop.close()
end_time=time.time()
print(end_time-start_time)
执行结果:
0 test2
0 test1
1 test2
1 test1
2 test2
3 test2
2 test1
4 test2
3 test1
5 test2
6 test2
4 test1
7 test2
5 test1
8 test2
9 test2
6 test1
10 test2
7 test1
11 test2
12 test2
8 test1
13 test2
9 test1
14 test2
30.00783109664917
可以看出,异步代码比同步代码的执行速度快了30秒。