天天看点

python异步编程_Python 中的异步编程:Asyncio

原标题:Python 中的异步编程:Asyncio

异步和同步的代码对比

现在我们实际验证异步模式的切实有效,我会比较两段 python 脚本,这两个脚本除了 sleep 方法外,其余部分完全相同。在第一个脚本里,我会用标准的 time.sleep 方法,在第二个脚本里使用 asyncio.sleep 的异步方法。

这里使用 Sleep 是因为它是一个用来展示异步方法如何操作 I/O 的最简单办法。

使用同步 sleep 方法的代码:

importasyncio importtime fromdatetime importdatetime asyncdefcustom_sleep():print('SLEEP', datetime.now()) time.sleep(1) asyncdeffactorial(name, number):f = 1fori inrange(2, number+1): print('Task {}: Compute factorial({})'.format(name, i)) awaitcustom_sleep() f *= i print('Task {}: factorial({}) is {}\n'.format(name, number, f)) start = time.time() loop = asyncio.get_event_loop() tasks = [ asyncio.ensure_future(factorial("A", 3)), asyncio.ensure_future(factorial("B", 4)), ] loop.run_until_complete(asyncio.wait(tasks)) loop.close() end = time.time() print("Total time: {}".format(end - start))

脚本输出:

TaskA: Computefactorial(2) SLEEP2017-04-0613:39:56.207479TaskA: Computefactorial(3) SLEEP2017-04-0613:39:57.210128TaskA: factorial(3) is6TaskB: Computefactorial(2) SLEEP2017-04-0613:39:58.210778TaskB: Computefactorial(3) SLEEP2017-04-0613:39:59.212510TaskB: Computefactorial(4) SLEEP2017-04-0613:40:00.217308TaskB: factorial(4) is24Totaltime: 5.016386032104492

使用异步 Sleep 的代码:

importasyncio importtime fromdatetime importdatetime asyncdefcustom_sleep():print('SLEEP {}\n'.format(datetime.now())) awaitasyncio.sleep(1) asyncdeffactorial(name, number):f = 1fori inrange(2, number+1): print('Task {}: Compute factorial({})'.format(name, i)) awaitcustom_sleep() f *= i print('Task {}: factorial({}) is {}\n'.format(name, number, f)) start = time.time() loop = asyncio.get_event_loop() tasks = [ asyncio.ensure_future(factorial("A", 3)), asyncio.ensure_future(factorial("B", 4)), ] loop.run_until_complete(asyncio.wait(tasks)) loop.close() end = time.time() print("Total time: {}".format(end - start))

脚本输出:

TaskA: Computefactorial(2) SLEEP2017-04-0613:44:40.648665TaskB: Computefactorial(2) SLEEP2017-04-0613:44:40.648859TaskA: Computefactorial(3) SLEEP2017-04-0613:44:41.649564TaskB: Computefactorial(3) SLEEP2017-04-0613:44:41.649943TaskA: factorial(3) is6TaskB: Computefactorial(4) SLEEP2017-04-0613:44:42.651755TaskB: factorial(4) is24Totaltime: 3.008226156234741

从输出可以看到,异步模式的代码执行速度快了大概两秒。当使用异步模式的时候(每次调用 await asyncio.sleep(1) ),进程控制权会返回到主程序的消息循环里,并开始运行队列的其他任务(任务A或者任务B)。

当使用标准的 sleep方法时,当前线程会挂起等待。什么也不会做。实际上,标准的 sleep 过程中,当前线程也会返回一个 python 的解释器,可以操作现有的其他线程,但这是另一个话题了。返回搜狐,查看更多

责任编辑: