Skip to content

Commit d7cc4a2

Browse files
authored
Refactor global counter and logging in functions
Refactor functions and fix global variable usage in functions_Helin_Harman.py.
1 parent 71f5b39 commit d7cc4a2

File tree

1 file changed

+86
-0
lines changed

1 file changed

+86
-0
lines changed

Week04/functions_Helin_Harman.py

Lines changed: 86 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,86 @@
1+
import inspect
2+
import time
3+
import tracemalloc
4+
from functools import wraps
5+
6+
7+
custom_power = lambda x, /, e=1: x**e
8+
result = custom_power(3)
9+
print(f"Custom Power Sonucu: {result}")
10+
11+
def custom_equation(x=0, y=0, /, a=1, *, b=1, c=1) -> float:
12+
"""
13+
This function calculates (x*a + y*b)/c
14+
"""
15+
return (x*a + y*b)/c
16+
17+
result1 = custom_equation(3, 4, 5, b=4, c=2)
18+
print(f"Custom Equation Sonucu: {result1}")
19+
20+
21+
global_counter = 0
22+
caller_log = {}
23+
24+
def fn_w_counter(c: int, d: dict) -> tuple[int, dict]:
25+
26+
global global_counter
27+
28+
caller_name = 'unknown_run'
29+
try:
30+
caller_name = inspect.stack()[1].f_globals.get('__name__', 'system_call')
31+
except (IndexError, AttributeError, ValueError):
32+
caller_name = 'ide_console'
33+
34+
global_counter += 1
35+
36+
caller_log[caller_name] = caller_log.get(caller_name, 0) + 1
37+
38+
return (global_counter, caller_log.copy())
39+
40+
def helper_test(val):
41+
return fn_w_counter(val, {})
42+
43+
44+
45+
def performance(func):
46+
@wraps(func)
47+
def _performance(*args, **kwargs):
48+
tracemalloc.start()
49+
t1 = time.perf_counter()
50+
51+
result = func(*args, **kwargs)
52+
53+
current, peak = tracemalloc.get_traced_memory()
54+
tracemalloc.stop()
55+
t2 = time.perf_counter()
56+
57+
_performance.counter += 1
58+
_performance.total_time += (t2 - t1)
59+
_performance.total_mem += peak
60+
61+
return result
62+
63+
_performance.counter = 0
64+
_performance.total_time = 0.0
65+
_performance.total_mem = 0
66+
return _performance
67+
68+
@performance
69+
def calculate_process_time(n):
70+
data = list(range(n))
71+
return sum(data)
72+
73+
74+
if __name__ == '__main__':
75+
print("\n--- fn_w_counter Testi ---")
76+
fn_w_counter(1, {})
77+
count2, log2 = fn_w_counter(2, {})
78+
count3, log3 = helper_test(3)
79+
print(f"Toplam Çağrı: {count3}, Caller Log: {log3}")
80+
81+
print("\n--- Performance Testi ---")
82+
calculate_process_time(500000)
83+
calculate_process_time(1000000)
84+
print(f"Toplam Çağrı Sayısı: {calculate_process_time.counter}")
85+
print(f"Toplam Süre: {calculate_process_time.total_time:.4f} sn")
86+
print(f"Toplam Bellek: {calculate_process_time.total_mem} byte")

0 commit comments

Comments
 (0)