来自命令行的 python 脚本的时间函数
Time function from python script from the command line
我想为脚本中的函数计时,最好不要修改所述脚本(即添加计时器装饰器或函数)。
从命令行,运行 timeit 模块作为脚本传递额外的 setup 参数 (-s)。安装程序应从脚本中导入您希望计时的功能。
最后,记得添加对该函数的调用。
警告:安装程序将 运行 一次,导入您的脚本。导入 运行 所有“未受保护的代码”,因此请记住使用 if __name__ == "__main__"
约定将 function/object 声明与实际执行分开。
想象一下script.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
我想为脚本中的函数计时,最好不要修改所述脚本(即添加计时器装饰器或函数)。
从命令行,运行 timeit 模块作为脚本传递额外的 setup 参数 (-s)。安装程序应从脚本中导入您希望计时的功能。
最后,记得添加对该函数的调用。
警告:安装程序将 运行 一次,导入您的脚本。导入 运行 所有“未受保护的代码”,因此请记住使用 if __name__ == "__main__"
约定将 function/object 声明与实际执行分开。
想象一下script.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