Created
February 14, 2018 12:27
-
-
Save andriykohut/5bee9789ee4fc84fad60482610b87f75 to your computer and use it in GitHub Desktop.
Async Decorator
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import time | |
import asyncio | |
from functools import wraps | |
from timeit import default_timer | |
def time_it(fn): | |
if asyncio.iscoroutinefunction(fn): | |
@wraps(fn) | |
async def wrapper(*args, **kwargs): | |
start = default_timer() | |
result = await fn(*args, **kwargs) | |
print(f'{fn.__name__} - took {default_timer() - start}s') | |
return result | |
else: | |
@wraps(fn) | |
def wrapper(*args, **kwargs): | |
start = default_timer() | |
result = fn(*args, **kwargs) | |
print(f'{fn.__name__} - took {default_timer() - start}s') | |
return result | |
return wrapper | |
@time_it | |
def test(): | |
time.sleep(3) | |
@time_it | |
async def test_async(): | |
await asyncio.sleep(3) | |
if __name__ == '__main__': | |
test() | |
loop = asyncio.get_event_loop() | |
result = loop.run_until_complete(test_async()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment