问题描述
我想从脚本中计时函数,最好不要修改所述脚本(即添加计时器装饰器或函数)。
解决方法
在命令行中,将 timeit 模块作为脚本运行,并传递附加的 setup 参数(-s)。安装程序应从脚本中导入您希望计时的功能。
最后,请记住将调用添加到该函数。
警告:安装程序将运行一次,导入脚本。导入会运行所有“不受保护的代码”,因此请记住使用if __name__ == "__main__"
约定将函数/对象声明与实际执行分开。
想象以下脚本。py
import time
print('This will be run on import')
def fun():
pass
def very_complex_function_that_takes_an_hour_to_run():
time.sleep(3600)
if __name__ == '__main__':
print("Nothing beyond the if condition will be run on import")
very_complex_function_that_takes_an_hour_to_run()
让我们fun
运行100次。
$ python -m timeit -s 'from test import fun' -n 100 'fun()'
输出
This will be run on import
100 loops,best of 5: 66.6 nsec per loop