将 callgrind/valgrind 附加到程序执行的中途

attaching callgrind/valgrind to program in mid-way of its execution

我使用 Valgrind 从一开始就通过 运行 程序检测问题。 现在我在程序的某个特定时刻遇到了 memory/performance 个问题。不幸的是,从一开始就没有可行的方法到这个地方。

有没有办法在 C++ 程序 ( Valgrind/Callgrind ) 的中途执行过程中检测它,比如附加到进程?

这里已经回答: How use callgrind to profiling only a certain period of program execution?

无法在已经 运行 的程序上使用 valgrind。

对于 callgrind,您可以通过仅在稍后执行期间记录数据来稍微加快它的速度。

为此,您可以例如查看 callgrind 选项

    --instr-atstart=no|yes    Do instrumentation at callgrind start [yes]
    --collect-atstart=no|yes  Collect at process/thread start [yes]
    --toggle-collect=<func>   Toggle collection on enter/leave function

您还可以在程序中控制这些方面。

有关详细信息,请参阅 valgrind/callgrind 用户手册。

Callgrind 有两件事会减慢执行速度。

  • 计数操作(收集部分)
  • 模拟缓存和分支预测器(检测部分)。这取决于 --cache-sim--branch-sim 选项,它们都默认为 "no"。如果您使用这些选项并禁用检测,那么我预计会对建模的准确性产生一些影响,因为缓存和预测器在切换时不会 "warm"。

您还可以使用其他几种方法。

  1. 使用客户端请求机制。这将需要您包含一个 Valgrind header 并添加几行使用 Valgrind 宏 CALLGRIND_START_INSTRUMENTATION/CALLGRIND_STOP_INSTRUMENTATIONCALLGRIND_TOGGLE_COLLECT 来启动和停止 instrumentation/collection。 See the manual 了解详情。然后 运行 您在 Valgrind 下的应用程序 --instr-atstart=no --collect-atstart=no

  2. 使用 gdb monitor commands。在这种情况下,您将有两个终端。首先,您将 运行 Valgrind 与 --instr-atstart=no --collect-atstart=no --vgdb=yes。在第二个终端 运行 gdb yourapplication 然后从 gdb 提示 (gdb) target remote | vgdb。然后你就可以使用手册中描述的监控命令,其中包括收集和检测控制。

  3. callgrind_control,Valgrind 发行版的一部分。老实说,我从来没有用过这个。

我最近在没有 cache/branch sim 的情况下使用第一种技术进行了一些分析。当我在整个 运行 上使用 Callgrind 时,与 运行 以外的 Callgrind 相比,我发现 运行 时间增加了 23 倍。当我只分析一个我想分析的函数时,速度下降了大约 5 倍。显然,这将在很大程度上视情况而定。

感谢大家的帮助。 似乎已经在这里回答了:How use callgrind to profiling only a certain period of program execution? 但由于某种原因未标记为已回答。

总结: 在仪器关闭的情况下启动 callgrind

valgrind --tool=callgrind --instr-atstart=no <PROG>

控制检测(可以在其他shell中执行)

callgrind_control -i on/off