Skip to content

Instantly share code, notes, and snippets.

@nngogol
Created December 20, 2020 22:51
Show Gist options
  • Save nngogol/84ed267539ee1cb4a8500b76e22de793 to your computer and use it in GitHub Desktop.
Save nngogol/84ed267539ee1cb4a8500b76e22de793 to your computer and use it in GitHub Desktop.
decorator with params!
#!/usr/bin/python3
'''
.-----------.
.| decorator |.
/ '-----------' \
/ \
/ \
/ \
----' '------
.-----------------. .------------------------------.
| <no args> | | with args |
| V | | V |
| @timeit | | @timeit(1,'2',['3', 3.1415]) |
| def func(): ... | | def func(): ... |
'-----------------' '------------------------------'
| |
v v
.------------. .-------------.
| use timeit | | use timeit2 |
'------------' '-------------'
'''
'''
Короче, декоратор без параметров - timeit
декоратор с параметрами - timeit2
'''
import time
def timeit(our_function):
def wrapper(*args, **kwargs):
# pre ...
start = time.time()
return_val = our_function(*args, **kwargs)
# post
end = time.time()
print(f'Начало в : ', start)
print(f'Окончено в : ', end)
print(f'Длительность: ', end - start)
return return_val
return wrapper
def timeit2(space=''):
def matreshka1(our_function):
def matreshka2(*args, **kwargs):
# pre ...
start = time.time()
return_val = our_function(*args, **kwargs)
end = time.time()
print(f'{space}Начало в : ', start)
print(f'{space}Окончено в : ', end)
print(f'{space}Длительность: ', end - start)
# post ...
return return_val
return matreshka2
return matreshka1
@timeit
def f1():
print('alice')
return 'bs1'
@timeit2('>>> ')
def f2():
print('bob')
return 150
@timeit2('>>> ')
def f3():
print('bob')
return 350
print('-'*30)
f1()
f2()
f3()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment