【问题标题】:cProfile , how to log the data to a filecProfile ,如何将数据记录到文件中
【发布时间】:2018-09-08 00:47:14
【问题描述】:

我是一个使用 python 的初学者,每次运行给定的模拟时,我都被要求记录配置文件。我的模拟有 4 个类和 10 个方法,它们循环运行,直到达到某个条件。

我已经编写了创建文件的以下文件:

LOG_FILE = open(os.path.join(os.getcwd(), "logs", "Log_Log_{}.txt".format(
   str(datetime.datetime.now()).replace(":", "_"))), mode="w") 

就在我添加的脚本的底部:

if __name__ == "__main__":
    cProfile.run("main()", LOG_FILE, sort="tottime")

为什么我的 Log_Log 文件为空白且 cProfile 没有返回任何内容?

【问题讨论】:

  • 使用 pstats 模块转储日志文件进行分析

标签: python profiling


【解决方案1】:

使用 pstats 以人类可读的格式转储 cProfile 的输出

def sample():
   # initialize cProfile
   profiler_object = cProfile.Profile()
   profiler_object.enable()

   # execute something here
   a = [i for i in range(0, 100)]

   profiler_object.disable()

   # dump the profiler stats 
   s = io.StringIO()
   ps = pstats.Stats(profiler_object, stream=s).sort_stats('cumulative')
   ps.dump_stats('enter your dump file path here')

   # convert to human readable format
   out_stream = open('enter your log file path here', 'w')
   ps = pstats.Stats('enter your dump file path here', stream=out_stream)
   ps.strip_dirs().sort_stats('cumulative').print_stats()
   return True

sample()

样本输出:

Sat Sep  8 07:07:34 2018    your_dump_file_path

     2 function calls in 0.000 seconds

     Ordered by: cumulative time

     ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.000    0.000    <ipython-input-31-4e18ee895e20>:4(<listcomp>)
        1    0.000    0.000    0.000    0.000    {method 'disable' of '_lsprof.Profiler' objects}

您可以使用decorators 即兴创作

def profiler(func):
     def wrapper(*args, **kwargs):
         # profiler initialization 
         res = func(*args, **kwargs)
         # further processing
     return wrapper


@profiler
def a():
    print('hello world')

【讨论】:

  • 您好,您所说的 ## all profiling code 是什么意思,然后是 ## 剩余代码?例如,我有 4 个类在运行,里面有几种方法。我在哪里放置探查器? tks
  • 您可以获得类中的所有方法,如下所述:stackoverflow.com/questions/37075680/run-all-functions-in-class 并运行分析器,如上所示(或者)您可以装饰类,如下所述:stackoverflow.com/questions/6307761/… 并运行分析器. #all 分析代码是指分析器初始化,其余代码是指转换为人类可读格式和其他操作,例如绘制图形(如果需要)等
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-06-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多