Skip to content

Instantly share code, notes, and snippets.

@andriykohut
Created February 14, 2018 12:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriykohut/5bee9789ee4fc84fad60482610b87f75 to your computer and use it in GitHub Desktop.
Save andriykohut/5bee9789ee4fc84fad60482610b87f75 to your computer and use it in GitHub Desktop.
Async Decorator
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