你打电话给你的
fib_gen_r
之前
打电话给
time_spend
. 相反,您必须将实际函数作为参数传递,而不调用它,并在内部调用它
花时间
.
time_spend(fib_gen_r(35))
电话
纤维发电机
首先,完成后,将结果传递给
. 不是你想要的,因为你无法衡量什么已经完成。相反,您希望使用此语法
time_spend(fib_gen_r, 35)
要将实际的函数对象作为参数传递,
不叫它
def time_spend(code_to_check, *args, **kwds):
import time
start_time = time.time()
result = code_to_check(*args, **kwds)
print(f"--- {time.time() - start_time}s seconds ---\n")
return result
time_spend(fib_gen_r, 35)
一个更简单的选择是使用上下文管理器(
with
import contextlib
@contextlib.contextmanager
def time_spend():
import time
start_time = time.time()
yield
print(f"--- {time.time() - start_time}s seconds ---\n")
然后你可以这样使用它:
with time_spend():
fib_gen_r(35)