【问题标题】:cProfile - keep data in Python object/defer write to diskcProfile - 将数据保存在 Python 对象中/延迟写入磁盘
【发布时间】:2013-03-26 06:41:36
【问题描述】:

我有一个想用 cProfile 分析的函数,但我还保存了很多关于结果的其他分析 - 这当前保存到一个以编程方式生成名称的目录中,我希望配置文件数据是保存在同一目录中。

但是:目录名称仅在我要分析的函数完成后在concurrent.futures 回调函数中计算出来。

有没有一种简单的方法可以将配置文件数据保存在 Python 对象中,一旦知道文件名,就可以将其传递给回调函数(例如,与函数的结果一起返回)以写入磁盘?

【问题讨论】:

    标签: python cprofile


    【解决方案1】:

    cProfile.py 中的 run() 函数看起来像这样(在 Python 2.7 中,但同样的方法也适用于 Python 3)。从那里您可以看到,如果您直接使用 Profile 对象,您可以在分析后将 dump_stats 放到您想要的位置。

    def run(statement, filename=None, sort=-1):
        """Run statement under profiler optionally saving results in filename
    
        This function takes a single argument that can be passed to the
        "exec" statement, and an optional file name.  In all cases this
        routine attempts to "exec" its first argument and gather profiling
        statistics from the execution. If no file name is present, then this
        function automatically prints a simple profiling report, sorted by the
        standard name string (file/line/function-name) that is presented in
        each line.
        """
        prof = Profile()
        result = None
        try:
            try:
                prof = prof.run(statement)
            except SystemExit:
                pass
        finally:
            if filename is not None:
                prof.dump_stats(filename)
            else:
                result = prof.print_stats(sort)
        return result
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-12-24
      • 2017-10-19
      • 1970-01-01
      • 1970-01-01
      • 2012-07-29
      • 2011-04-09
      相关资源
      最近更新 更多