[英]run time check function
我知道我可以使用时间模块来跟踪代码的运行时间:
例如,如果我具有递归的斐波那契函数
def fib_gen_r(i):
"""
Fibonacci function generator
generate the fibonacci number at 'i'th posistion
"""
if i == 0:
return 0
elif i == 1:
return 1
else:
return fib_gen_r(i - 1) + fib_gen_r(i - 2)
我可以做这个:
import time
start_time = time.time()
print(fib_gen_r(35))
print(f"--- {time.time() - start_time}s seconds ---\n")
# >>>
# 9227465
# --- 2.556117296218872s seconds ---
但是,如果我不想每次都写这个,我写了一个函数:
def time_spend(code_to_check):
import time
start_time = time.time()
print(code_to_check)
print(f"--- {time.time() - start_time}s seconds ---\n")
time_spend(fib_gen_r(35))
# >>>
# check run-time:
# 9227465
# --- 0.0s seconds ---
不知何故,它没有读取运行时,我做错了什么?
谢谢,
你在呼唤你的fib_gen_r
调用之前函数time_spend
。 相反,您必须将实际函数作为参数传递,而无需调用它,而必须在time_spend
内部调用它。
此代码time_spend(fib_gen_r(35))
首先调用fib_gen_r
,完成后将结果传递给time_spend
。 不是您想要的,因为您无法衡量已经完成的事情。 相反,您想使用这种语法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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.