00. 同期処理のコード
import time
def sync_func():
for i in range(10):
time.sleep(0.5)
print(i)
start = time.time()
sync_func()
end=time.time()
print(end-start)
01. 非同期処理のコード
import asyncio
import time
async def sync_func():
for i in range(10):
await asyncio.sleep(0.5) #eventloop not blocked
print(i)
start = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(sync_func())
loop.close()
end=time.time()
print(end-start)
02. 同期処理コード vs. 非同期処理コード
import time
def sync_func():
for i in range(10):
time.sleep(0.5)
print(i)
start = time.time()
sync_func()
sync_func()
sync_func()
end=time.time()
print(end-start)
result
0
1
2
3
...
0
1
2
...
0
...
9
15.031020402908325
import time
import asyncio
async def sync_func():
for i in range(10):
await asyncio.sleep(0.5) #eventloop not blocked
print(i)
start = time.time()
loop = asyncio.get_event_loop()
loop.run_until_complete(asyncio.gather(sync_func(),sync_func(),sync_func(),))
loop.close()
end=time.time()
print(end-start)
result
0
0
0
1
1
1
...
9
9
9
5.013215065002441