Skip to content

Commit fc28c11

Browse files
authored
Create decorators_aysegul_ezber.py
1 parent f43056e commit fc28c11

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

Week04/decorators_aysegul_ezber.py

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import time
2+
import tracemalloc
3+
4+
def performance_decorator(func):
5+
"""
6+
A decorator to measure the performance of the decorated function.
7+
It tracks the execution time and memory usage and stores statistics.
8+
"""
9+
# Initialize performance attributes for the decorator
10+
def init_performance_attrs():
11+
setattr(func, 'counter', 0) # Count the number of times the function is called
12+
setattr(func, 'total_time', 0.0) # Total execution time
13+
setattr(func, 'total_mem', 0.0) # Total memory used
14+
15+
# Initialize performance tracking for the first time
16+
if not hasattr(func, 'counter'):
17+
init_performance_attrs()
18+
19+
def wrapper(*args, **kwargs):
20+
# Access the current performance attributes
21+
counter = getattr(func, 'counter')
22+
total_time = getattr(func, 'total_time')
23+
total_mem = getattr(func, 'total_mem')
24+
25+
# Start memory tracking
26+
tracemalloc.start()
27+
28+
# Start the timer to measure execution time
29+
start_time = time.time()
30+
31+
try:
32+
# Execute the original function
33+
result = func(*args, **kwargs)
34+
except Exception as e:
35+
# Handle any exceptions raised during function execution
36+
print(f"Error occurred while executing {func.__name__}: {e}")
37+
result = None
38+
finally:
39+
# End the timer and stop memory tracking
40+
end_time = time.time()
41+
current, peak = tracemalloc.get_traced_memory()
42+
tracemalloc.stop()
43+
44+
# Calculate time taken and memory used
45+
elapsed_time = end_time - start_time
46+
memory_usage = peak
47+
48+
# Update performance statistics
49+
counter += 1
50+
total_time += elapsed_time
51+
total_mem += memory_usage
52+
53+
# Save updated statistics back to the function attributes
54+
setattr(func, 'counter', counter)
55+
setattr(func, 'total_time', total_time)
56+
setattr(func, 'total_mem', total_mem)
57+
58+
# Print performance results
59+
print(f"Function '{func.__name__}' executed.")
60+
print(f"Execution time: {elapsed_time:.6f} seconds")
61+
print(f"Memory usage: {memory_usage / 1024:.2f} KB")
62+
print(f"Total calls: {counter}")
63+
print(f"Total time: {total_time:.6f} seconds")
64+
print(f"Total memory used: {total_mem / 1024:.2f} KB")
65+
66+
return result
67+
68+
return wrapper
69+
70+
# Example usage of the decorator
71+
72+
@performance_decorator
73+
def example_function(n):
74+
"""
75+
A simple function that simulates some work by sleeping.
76+
The function calculates the sum of numbers up to n and returns it.
77+
"""
78+
total = sum(range(n))
79+
time.sleep(0.5) # Simulate some work
80+
return total
81+
82+
# Calling the decorated function
83+
example_function(1000)
84+
example_function(5000)
85+
example_function(10000)

0 commit comments

Comments
 (0)