Skip to content

Commit c0b3e43

Browse files
author
Gennadii Kandaurov
committed
add lesson #02
1 parent 923b2b0 commit c0b3e43

File tree

1 file changed

+59
-0
lines changed

1 file changed

+59
-0
lines changed

lesson-02/decos.py

Lines changed: 59 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,59 @@
1+
import time
2+
3+
def time_it(fn):
4+
def inner_func(*args, **kwargs):
5+
start = time.time()
6+
try:
7+
res = fn(*args, **kwargs)
8+
finally:
9+
print(time.time() - start)
10+
return res
11+
12+
return inner_func
13+
14+
15+
@time_it
16+
def sleep_func(sec):
17+
print(f'run with {sec}')
18+
raise RuntimeError
19+
time.sleep(sec)
20+
21+
22+
def deco(add_param):
23+
def inner_deco(fn):
24+
def inner(*args, **kwargs):
25+
return fn(*args, **kwargs) + add_param
26+
return inner
27+
return inner_deco
28+
29+
30+
def time_it_avg(k):
31+
last_calls = []
32+
def time_it(fn):
33+
def inner_func(*args, **kwargs):
34+
start = time.time()
35+
try:
36+
res = fn(*args, **kwargs)
37+
finally:
38+
last_time = time.time() - start
39+
print(last_time)
40+
last_calls.append(last_time)
41+
print(sum(last_calls[-k:]) / min(len(last_calls), k))
42+
return res
43+
44+
return inner_func
45+
return time_it
46+
47+
48+
@time_it_avg(2)
49+
def sleep_func_1(sec):
50+
print(f'run with {sec}')
51+
# raise RuntimeError
52+
time.sleep(sec)
53+
54+
55+
if __name__ == '__main__':
56+
sleep_func_1(0.1)
57+
sleep_func_1(0.5)
58+
sleep_func_1(1.0)
59+

0 commit comments

Comments
 (0)