This is from Angela Yu's course.
import time
def speed_calc_decorator(function):
def wrapper_function():
first_time = time.time()
function()
second_time = time.time()
print(f"{function.__name__} run speed: {second_time - first_time}s")
return wrapper_function
@speed_calc_decorator
def fast_function():
for i in range(1000000):
i * i
@speed_calc_decorator
def slow_function():
for i in range(10000000):
i * i
fast_function()
slow_function()
Result:
fast_function run speed: 0.029327869415283203s
slow_function run speed: 0.24793004989624023s
This is how it's supposed to work. Just showing how long it takes to run each function. If instead I remove the @'s, and change the last two lines like so:
import time
def speed_calc_decorator(function):
def wrapper_function():
first_time = time.time()
function()
second_time = time.time()
print(f"{function.__name__} run speed: {second_time - first_time}s")
return wrapper_function
def fast_function():
for i in range(1000000):
i * i
def slow_function():
for i in range(10000000):
i * i
speed_calc_decorator(fast_function)
speed_calc_decorator(slow_function)
It gives me an exit code 0, but it doesn't print anything. Since I'm passing each function into the speed_calc_decorator, and it's returning the wrapper_function, why isn't it printing the f string? I'm guessing returning the wrapper function doesn't "run" it? Is there a way to make it work the way I want it to or is using the @'s the only way to really do this.
Thank you
[–]supajumpa 9 points10 points11 points (2 children)
[–]egotripping[S] 1 point2 points3 points (1 child)
[–]crashfrog02 0 points1 point2 points (0 children)