cProfile - 将数据保存在Python对象中/延迟写入磁盘

时间:2013-03-26 06:41:37

标签: python cprofile

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

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

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

1 个答案:

答案 0 :(得分:1)

run()中的cProfile.py函数看起来像这样(在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