假设我有一个函数 void Myclass::func(x)
,而其他各种代码对它进行了数千次调用。现在我想知道参数 x
的一些统计数据,例如平均值、最大值、最小值,甚至分布图。
void Myclass::func(int x) {
while(foo.doFancyStuff(x)) {
// ...
}
}
这是我想到的一些临时方法:
- 打印
x
的每个值以记录。然后使用外部工具/脚本来分析它们。- 注意事项:与日志中的其他信息混合。将
x
的每个值写入外部日志或文件系统上的文件很慢。
- 注意事项:与日志中的其他信息混合。将
- 定义全局变量来存储它们并在感兴趣的执行结束时进行分析。
- 警告:全局变量不好。他们将来会变得困惑。
- 将它们存储在
Myclass
类中。- 警告:不可重复使用的代码。下次我想分析
Otherclass::doOtherStuff(y)
怎么办?并且集成不好,因为统计代码不应该与Myclass
本身耦合。
- 警告:不可重复使用的代码。下次我想分析
是否有任何工具/库可以执行此操作?我在 Windows 上使用 Visual Studio,所以想要一个可用于该平台的答案。也欢迎使用跨平台工具。
最佳答案
这是一个使用 lldb
脚本 API 的示例(也适用于 Windows)。以这个简单的程序为例,
void func(int x) {}
int main(int, char **)
{
for (int i = 0; i < 1000; ++i)
func(i);
}
你可以用这样的脚本来分析
import lldb
import os
fArgs = []
def analyzeFrame(frame, bpLocation, dict):
variables = frame.GetVariables(True, False, False, False)
x = variables.GetValueAtIndex(0).GetValueAsSigned()
fArgs.append(x)
return False
debugger = lldb.SBDebugger.Create()
debugger.SetAsync(False)
target = debugger.CreateTargetWithFileAndArch("pathToYourExecutable", "")
bp = target.BreakpointCreateByName("func", 4, lldb.SBFileSpecList(), lldb.SBFileSpecList())
bp.SetScriptCallbackFunction("analyzeFrame")
process = target.Launch(target.GetDebugger().GetListener(), [], [],
None, None, None, os.getcwd(), 0, False, lldb.SBError())
print("max: {}".format(max(fArgs)))
print("min: {}".format(min(fArgs)))
您需要确保 python 解释器找到 lldb
模块。在命令行执行lldb -P
可以看到路径。
关于c++ - 在调试中,如何知道函数重复调用中参数的统计信息(最大-最小值、平均值、分布...)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54399218/