Skip to content

Commit 3eb1d59

Browse files
authored
Implement performance measuring decorator
Add a performance decorator to measure function execution time and memory usage.
1 parent 71f5b39 commit 3eb1d59

File tree

1 file changed

+50
-0
lines changed

1 file changed

+50
-0
lines changed

Week04/decorators_Helin_Harman.py

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
import time
2+
import functools
3+
import tracemalloc
4+
5+
def performance(func):
6+
"""
7+
Fonksiyon performansını ölçen ve istatistikleri (sayaç, süre, bellek)
8+
kendi özniteliklerinde saklayan bir dekoratör.
9+
"""
10+
@functools.wraps(func)
11+
def wrapper(*args, **kwargs):
12+
13+
wrapper.counter += 1
14+
15+
16+
tracemalloc.start()
17+
start_time = time.perf_counter()
18+
19+
try:
20+
result = func(*args, **kwargs)
21+
return result
22+
finally:
23+
24+
end_time = time.perf_counter()
25+
duration = end_time - start_time
26+
wrapper.total_time += duration
27+
28+
29+
_, peak = tracemalloc.get_traced_memory()
30+
wrapper.total_mem += peak
31+
tracemalloc.stop()
32+
33+
wrapper.counter = 0
34+
wrapper.total_time = 0.0
35+
wrapper.total_mem = 0
36+
37+
return wrapper
38+
39+
@performance
40+
def test_function(n):
41+
42+
return [i**2 for i in range(n)]
43+
44+
if __name__ == "__main__":
45+
test_function(100000)
46+
test_function(200000)
47+
48+
print(f"Fonksiyon {test_function.counter} kez çağrıldı.")
49+
print(f"Toplam süre: {test_function.total_time:.4f} saniye")
50+
print(f"Toplam bellek tüketimi: {test_function.total_mem} byte")

0 commit comments

Comments
 (0)