微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何使用 snakeviz 和 cProfile

如何解决如何使用 snakeviz 和 cProfile

所以您想知道为什么您的 Python 脚本运行缓慢?

使用 cProfile 和 pstats 有一种简单的方法可以做到这一点,它们计算每个函数调用次数。我们可以使用 snakeviz 在我们的 Web 浏览器中以交互方式可视化结果。 您需要 pip install snakeviz,但其他两个包含在认 Python 库中。

我最初一直在寻找一种在 PyCharm 中的单个 Python 脚本中完成所有这些工作的方法,但在仅找到涉及移动到终端运行 snakeviz 的解决方案后,我设法通过查看 snakeviz 自己解决了这个问题源代码。我认为如果我分享我最近的发现会对社区有益。有关如何创建简单的包装函数并将其传递以进行速度测试的详细信息,请参见下文。

解决方法

以下代码显示了如何通过将脚本放入包装器并传递该包装器进行分析来加速测试脚本。完成后,该功能应自动在浏览器中打开一个新选项卡以显示结果。

# this function does all the magic
# it accepts any function you want to speed test
# then it performs the test,analyses the results,and provides the output in your browser
def speedtest(function_wrapper):
    import cProfile
    import pstats
    import snakeviz.cli as cli

    with cProfile.Profile() as pr:
        function_wrapper()
    stats = pstats.Stats(pr)
    stats.sort_stats(pstats.SortKey.TIME)
    filename = "speedtest_profile.prof"
    stats.dump_stats(filename=filename)
    cli.main([filename])


# simply place the code you want to speed test inside a wrapper function
# it can be called anything but wrapper is used here
def wrapper():
    from reliability.Fitters import Fit_Weibull_2P
    from reliability.Distributions import Weibull_Distribution

    data = Weibull_Distribution(alpha=50,beta=2).random_samples(1000000,seed=1)
    Fit_Weibull_2P(failures=data,show_probability_plot=False,print_results=False)


# this executes the speedtest on the wrapper function
speedtest(wrapper)

结果如下:

results_in_browser

由此我可以清楚地看到,我应该努力加快 Probability_plotting.plotting_positions 函数的运行速度。如果您想知道,我包装的函数是从威布尔分布生成 100 万个样本,然后将 2 参数威布尔分布拟合到这些样本。我想看看这个过程的哪些部分花费的时间最长。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。