如何清除/重置 Python 线分析器的结果?



我正在尝试在运行时多次启动和停止 Python 函数的行分析。因此,我想在开始新的分析时重置已收集的统计信息。有没有办法做到这一点?

在缺乏明显的解决方案的情况下,我还尝试用一个新的实例替换线剖面仪lp

#!/usr/bin/env python3
from line_profiler import LineProfiler
lp = LineProfiler()
@lp
def count():
return sum(range(1_000_000))
count()
lp.print_stats()
# reset line profiler
new_lp = LineProfiler()
for f in lp.functions:
new_lp(f)
lp = new_lp
count()
lp.print_stats()

但不知何故,新的统计数据是空的,可能是因为函数count()不能包装两次?

我基于一个新的探查器类提出了以下解决方案。每次启动性能分析时,它都会创建一个新的LineProfiler实例。关键是将包装的函数存储在原始函数旁边,以便在停止探查器时可以重置它们。

from typing import Optional
from line_profiler import LineProfiler
from functools import wraps
class MyLineProfiler:
def __init__(self):
self.functions: list[list] = []
self.line_profiler: Optional[LineProfiler] = None
def __call__(self, func):
index = len(self.functions)
@wraps(func)
def wrap(*args, **kw):
return self.functions[index][1](*args, **kw)
self.functions.append([func, func])
return wrap
def start(self):
self.line_profiler = LineProfiler()
for f in self.functions:
f[1] = self.line_profiler(f[0])
def stop(self, *, print: bool = True):
for f in self.functions:
f[1] = f[0]
if self.line_profiler and print:
self.line_profiler.print_stats()
def reset(self):
self.stop(print=False)
self.start()

包装的函数调用当前存储在functions[index][1]的任何内容,可以是原始func(当没有停止分析时)或装饰的(当调用start()时)。

它可以按如下方式使用:

profile = MyLineProfiler()
@profile
def count():
return sum(range(1_000_000))
count()
profile.start()
count()
count()
profile.stop()
profile.start()
count()
profile.stop()

最新更新