cProfile - 保留Python对象中的数据/延迟写入磁盘

问题描述:

我有一个函数,我想用cProfile进行分析,但是我也保存了很多关于结果的其他分析 - 这当前被保存到一个名为以编程方式生成,我希望配置文件数据保存在同一个目录中。cProfile - 保留Python对象中的数据/延迟写入磁盘

但是:只有在我想要配置文件的功能完成后,才能在concurrent.futures回调函数中找到目录名称。

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

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