diff --git a/Week04/decorators_veli_unusdu.py b/Week04/decorators_veli_unusdu.py new file mode 100644 index 00000000..3fd85c5b --- /dev/null +++ b/Week04/decorators_veli_unusdu.py @@ -0,0 +1,23 @@ +import time, tracemalloc +from functools import wraps + +def performance(func): + performance.c = performance.c + 1 if hasattr(performance, "c") else 1 + performance.t = getattr(performance, "t", 0.0) + performance.m = getattr(performance, "m", 0) + + @wraps(func) + def wrapper(*a, **k): + performance.c += 1 + t0 = time.perf_counter() + tracemalloc.start() + r = func(*a, **k) + performance.t += time.perf_counter() - t0 + performance.m += tracemalloc.get_traced_memory()[1] + tracemalloc.stop() + return r + return wrapper + +performance.counter = 0 +performance.total_time = 0.0 +performance.total_mem = 0 diff --git a/Week04/test_decorators.py b/Week04/test_decorators.py deleted file mode 100644 index 2f89b9fb..00000000 --- a/Week04/test_decorators.py +++ /dev/null @@ -1,44 +0,0 @@ -import os -import inspect -import time -import random - - -files = [f for f in os.listdir(os.path.dirname(__file__)) if f.startswith("decorators")] -for f in files: - exec("import " + f[:-3] + " as " + f[:-3]) - - -def test_names(): - for f in files: - assert "performance" in dir(eval(f[:-3])), "timer is not defined in " + f[:-3] - -def test_callables(): - for f in files: - assert callable(eval(f[:-3]).performance), "timer is not callable in " + f[:-3] - -def test_performance(): - for f in files: - @eval(f[:-3]).performance - def dummy_timer(x): - time.sleep(x) - @eval(f[:-3]).performance - def dummy_memory(x): - return [random.randint(0, 100) for _ in range(x)] - dummy_timer(1) - assert eval(f[:-3]).performance.counter == 1, \ - "performance is not working in " + f[:-3] + " (counter)" - assert eval(f[:-3]).performance.total_time > 1, \ - "performance is not working in " + f[:-3] + " (total_time)" - dummy_timer(1) - dummy_timer(2) - dummy_timer(3) - assert eval(f[:-3]).performance.counter == 4, \ - "performance is not working in " + f[:-3] + " (counter)" - assert eval(f[:-3]).performance.total_time > 7, \ - "performance is not working in " + f[:-3] + " (total_time)" - dummy_memory(1000000) - assert eval(f[:-3]).performance.counter == 5, \ - "performance is not working in " + f[:-3] + " (counter)" - assert eval(f[:-3]).performance.total_mem > 8.e6, \ - "performance is not working in " + f[:-3] + " (total_mem)"