计算python脚本执行时间的最简单方法?

2024-04-19 17:47:30 发布

您现在位置:Python中文网/ 问答频道 /正文

计算Python脚本的执行时间最简单的方法是什么?


Tags: 方法脚本时间
3条回答

像这样使用Linux time命令:time python file.py

或者你可以在开始和结束时计算出时间差。

在linux下: 时间python script.py

timeit模块是专门为此目的而设计的。

愚蠢的例子如下

def test():
    """Stupid test function"""
    L = []
    for i in range(100):
        L.append(i)

if __name__ == '__main__':
    from timeit import Timer
    t = Timer("test()", "from __main__ import test")
    print t.timeit()

Note that timeit can also be used from the command line (python -m timeit -s 'import module' 'module.test()') and that you can run the statement several times to get a more accurate measurement. Something I think time command doesn't support directly. -- jcollado

相关问题 更多 >