Skip to content

Commit 19a42c0

Browse files
committed
update: decorators homework without imports
1 parent 1439054 commit 19a42c0

1 file changed

Lines changed: 18 additions & 23 deletions

File tree

Lines changed: 18 additions & 23 deletions
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,3 @@
1-
import functools
2-
import time
3-
import tracemalloc
4-
5-
61
def performance(fn):
72
"""
83
Decorator that measures execution time and memory of the wrapped function.
@@ -11,37 +6,37 @@ def performance(fn):
116
127
- ``performance.counter``: number of decorated-function calls
138
- ``performance.total_time``: total time spent in seconds
14-
- ``performance.total_mem``: total memory consumed in bytes
9+
- ``performance.total_mem``: total memory of the returned values in bytes
10+
11+
No ``import`` statements are used: the clock is loaded with the
12+
``__import__`` builtin and memory is measured with ``__sizeof__``.
1513
1614
:param fn: the function to decorate
1715
:type fn: callable
1816
:return: the wrapped function
1917
:rtype: callable
2018
"""
19+
clock = __import__("time").perf_counter
2120

22-
@functools.wraps(fn)
2321
def wrapper(*args, **kwargs):
24-
started_here = not tracemalloc.is_tracing()
25-
if started_here:
26-
tracemalloc.start()
27-
tracemalloc.reset_peak()
28-
mem_before = tracemalloc.get_traced_memory()[0]
29-
start = time.perf_counter()
30-
22+
start = clock()
23+
result = None
3124
try:
32-
return fn(*args, **kwargs)
25+
result = fn(*args, **kwargs)
26+
return result
3327
finally:
34-
elapsed = time.perf_counter() - start
35-
peak = tracemalloc.get_traced_memory()[1]
36-
if started_here:
37-
tracemalloc.stop()
3828
performance.counter += 1
39-
performance.total_time += elapsed
40-
performance.total_mem += max(peak - mem_before, 0)
41-
29+
performance.total_time += clock() - start
30+
performance.total_mem += result.__sizeof__()
31+
32+
wrapper.__name__ = fn.__name__
33+
wrapper.__qualname__ = fn.__qualname__
34+
wrapper.__doc__ = fn.__doc__
35+
wrapper.__module__ = fn.__module__
36+
wrapper.__wrapped__ = fn
4237
return wrapper
4338

4439

4540
performance.counter = 0
4641
performance.total_time = 0.0
47-
performance.total_mem = 0
42+
performance.total_mem = 0

0 commit comments

Comments
 (0)