我知道timeit可以用来衡量经过的时间,但我不知道如何在我的代码中实现。例如,我将评估模型性能如下:
scores = model.evaluate(X_test, Y_test, verbose=0)
如何添加timeit或其他一些功能来衡量所需的时间?
答案 0 :(得分:2)
这是一个基本设置:
import time
start_time = time.time()
# code
print("time - {}".format(time.time()-start_time))
您还可以使用Python的函数包装器,并创建一个包装器来为您的函数计时。例如
import time
def getime(func):
def func_wrapper(*args, **kwargs):
start_time = time.time()
func(*args, **kwargs)
print("function {} completed in - {} seconds".format(
func.__name__,
time.time()-start_time))
return func_wrapper
# ------------ test example of wrapper --------- #
@getime
def foo():
for i in range(1000):
for j in range(2000):
pass
foo()
<强>输出:强>
function foo completed in - 0.13300752639770508 seconds
答案 1 :(得分:1)
尝试:
import time
...
t = time.time()
scores = model.evaluate(X_test, Y_test, verbose=0)
elapsed_time = time.time()-t
要检查10000次(为了更准确),请尝试:
def check():
t = time.time()
scores = model.evaluate(X_test, Y_test, verbose=0)
elapsed_time = time.time()-t
return elapsed_time
average_elapsed_time = [sum(check() for i in range(10000))/10000][0]