You cannot select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
33 lines
768 B
Python
33 lines
768 B
Python
6 years ago
|
# https://djangostars.com/blog/asynchronous-programming-in-python-asyncio/
|
||
|
|
||
|
import asyncio
|
||
|
import time
|
||
|
from datetime import datetime
|
||
|
|
||
|
|
||
|
async def custom_sleep():
|
||
|
print('SLEEP {}n'.format(datetime.now()))
|
||
|
await asyncio.sleep(1)
|
||
|
|
||
|
async def factorial(name, number):
|
||
|
f = 1
|
||
|
for i in range(2, number+1):
|
||
|
print('Task {}: Compute factorial({})'.format(name, i))
|
||
|
await custom_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))
|