I want to eavalute the time needed to perform prediction using a trained model
本问题已经有最佳答案,请猛点这里访问。
我知道时间它可以用来测量经过的时间,但我不知道如何在代码中实现。例如,我将对模型性能进行如下评估:
1 | scores = model.evaluate(X_test, Y_test, verbose=0) |
如何添加timeit或其他一些函数来测量所需的时间?
以下是基本设置:
1 2 3 4 | import time start_time = time.time() # code print("time - {}".format(time.time()-start_time)) |
您还可以使用Python的函数包装器,并制作一个包装器来给函数计时。如。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | 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() |
输出:
1 | function foo completed in - 0.13300752639770508 seconds |
尝试:
1 2 3 4 5 | import time ... t = time.time() scores = model.evaluate(X_test, Y_test, verbose=0) elapsed_time = time.time()-t |
要检查10000次(为了更准确),请尝试:
1 2 3 4 5 6 | 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] |