Below are 2 examples that run sleep for 1 and 2 seconds each using async
/ await
syntax and using threads. The results are seemingly the same but I think they fundamentally work differently. In which case, when to use async
vs a thread?
import asyncio
import threading
import time
from datetime import timedelta
async def say_after(delay, what):
await asyncio.sleep(delay)
print(what)
async def async_tasks():
start_time = time.perf_counter()
task1 = asyncio.create_task(say_after(1, 'hello'))
task2 = asyncio.create_task(say_after(2, 'world'))
await task1
await task2
print(f'async time: {timedelta(seconds=time.perf_counter() - start_time)}')
def say_after2(delay, what):
time.sleep(delay)
print(what)
def threads():
start_time = time.perf_counter()
task1 = threading.Thread(target=say_after2, args=(1, 'hello'))
task2 = threading.Thread(target=say_after2, args=(2, 'world'))
task1.start()
task2.start()
task1.join()
task2.join()
print(f'threads time: {timedelta(seconds=time.perf_counter() - start_time)}')
if __name__ == '__main__':
asyncio.run(async_tasks())
threads()
hello
world
async time: 0:00:02.002056
hello
world
threads time: 0:00:02.004553