让cProf只给出10个最耗时的任务或者按照时间倒序对它们进行排序

Cat*_*ina 9 python time profiling compilation

我在终端上运行以下代码行来获取我的程序的配置文件。

python3 -m cProfile -s time main.py
Run Code Online (Sandbox Code Playgroud)

然而它打印的输出是巨大的。我只想知道 10 个最耗时的任务或按升序对它们进行排序。我怎样才能把这个告诉cprof?

小智 6

要打印名为“function_to_profile”的函数的 10 个最耗时的任务,您可以运行以下命令:

if __name__ == "__main__":
    import cProfile
    from pstats import Stats

    pr = cProfile.Profile()
    pr.enable()

    function_to_profile()

    pr.disable()
    stats = Stats(pr)
    stats.sort_stats('tottime').print_stats(10)
Run Code Online (Sandbox Code Playgroud)


Mik*_*sky 4

我在另一个答案中找到了解决方案。解决方案是在要分析的脚本内部使用 cProfile,而不是在命令行外部使用。

我的脚本如下所示:

def run_code_to_be_profiled():
    pass

if __name__ == "__main__":
    import cProfile

    pr = cProfile.Profile()
    pr.enable()

    run_code_to_be_profiled()

    pr.disable()
    pr.print_stats(sort='time')
Run Code Online (Sandbox Code Playgroud)

我运行该脚本并获得有用的输出。