Python async异步编程与同步对比

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秒。

  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值