Created
December 20, 2020 22:51
-
-
Save nngogol/84ed267539ee1cb4a8500b76e22de793 to your computer and use it in GitHub Desktop.
decorator with params!
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
#!/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