0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

非同期処理の覚書

Posted at

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

0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?