如何分析 Python 脚本?

发布于 2022-03-22 23:30:13

Project Euler和其他编码竞赛通常有最长的运行时间,或者人们吹嘘他们的特定解决方案运行速度有多快。使用 Python,有时这些方法有些笨拙 - 即,将计时代码添加到__main__.

什么是分析 Python 程序运行时间的好方法?

关注者
0
被浏览
63
1 个回答
  • 面试哥
    面试哥 2022-03-22
    为面试而生,有面试问题,就找面试哥。

    Python 包含一个名为cProfile的分析器。它不仅给出了总运行时间,而且还分别计算了每个函数的时间,并告诉你每个函数被调用了多少次,从而很容易确定你应该在哪里进行优化。

    您可以从代码中或从解释器中调用它,如下所示:

    import cProfile
    cProfile.run('foo()')
    

    更有用的是,您可以在运行脚本时调用 cProfile:

    python -m cProfile myscript.py
    

    为了使它更容易,我制作了一个名为“profile.bat”的小批处理文件:

    python -m cProfile %1
    

    所以我所要做的就是运行:

    profile euler048.py
    

    我明白了:

    1007 function calls in 0.061 CPU seconds
    
    Ordered by: standard name
    ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.061    0.061 <string>:1(<module>)
     1000    0.051    0.000    0.051    0.000 euler048.py:2(<lambda>)
        1    0.005    0.005    0.061    0.061 euler048.py:2(<module>)
        1    0.000    0.000    0.061    0.061 {execfile}
        1    0.002    0.002    0.053    0.053 {map}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Profiler objects}
        1    0.000    0.000    0.000    0.000 {range}
        1    0.003    0.003    0.003    0.003 {sum}
    


知识点
面圈网VIP题库

面圈网VIP题库全新上线,海量真题题库资源。 90大类考试,超10万份考试真题开放下载啦

去下载看看