为了账号安全,请及时绑定邮箱和手机立即绑定

来自命令行的Python脚本的时间函数

来自命令行的Python脚本的时间函数

青春有我 2023-12-29 10:06:52
我想从脚本中计时函数,最好不要修改所述脚本(即添加计时器装饰器或函数)。
查看完整描述

1 回答

?
慕的地10843

TA贡献1785条经验 获得超8个赞

从命令行,将timeit模块作为传递附加设置参数 (-s)的脚本运行。设置应该从脚本中导入您想要计时的函数。

最后,记住添加对该函数的调用。

警告:安装程序将运行一次,导入您的脚本。导入运行所有“不受保护的代码”,因此请记住使用if __name__ == "__main__"约定将函数/对象声明与实际执行分开。

想象一下以下 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


查看完整回答
反对 回复 2023-12-29
  • 1 回答
  • 0 关注
  • 42 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信