【问题标题】:Profiling a C++ project in terms of execution time根据执行时间分析 C++ 项目
【发布时间】:2012-06-13 00:22:34
【问题描述】:

我需要一些帮助来分析现有代码的执行时间。目的是加快速度。

我收到了一些以前处理过的代码。它完全用 C++ 编写,带有 OO 概念。它有一个基于 GUI 的界面,选择某个选项会运行选定的代码段。 (作为项目的一部分,大约有 11 个类)。

我希望能够按下 GUI 选项并让代码运行并生成如下资源映射:

Functions of Class 1 = 20% of execution time
Functions of Class 2 = 60% of execution time
Functions of Class 3 = 10% of execution time
Functions of Class 4 = 10% of execution time

这样,我知道哪个课程占用的时间最多,然后知道要学习和改进哪个课程。但是,我不知道该怎么做。我只有基本的 C++ 知识。

我确实读过这篇文章:find c++ execution time,但是由于该程序不是串行的。一个类调用另一个类,然后调用另一个类,我不知道系统时钟/刻度如何实现?

我读过 Valgrind、Zoom、Poor Man's Profiler 等程序,但老实说不知道如何将它与代码集成。有这么简单的方法吗?

我也读过这个方法:How can I profile C++ code running in Linux?,但是我不知道如何获得关于基于类的信息(1 类、2 类等)的精确信息

有人可以为新手提供建议吗?

【问题讨论】:

标签: c++ performance


【解决方案1】:

Valgrind(子工具 callgrind)使用起来非常简单。您只需确保将足够的调试信息编译/链接到您的程序中,以便 callgrind 可以找到被调用的各种函数的名称。然后,不要直接调用您的程序,而是将其(及其参数)作为参数传递给 valgrind,例如:

valgrind --tool=callgrind --trace-children=yes <myprogram> <myprogram_args>

(--trace-children 存在,以防您的真正可执行文件隐藏在某些层或多层包装脚本之后)

请注意,您的程序运行速度会慢得多(例如慢 100 倍),因为正在跟踪每个函数入口点。

存在各种工具来探索 callgrind 的输出,特别是 kcachegrind/qcachegrid。

或者,您可以测量少量高级函数的系统时钟节拍(因此您会看到“函数 X 及其下的所有内容所花费的时间”),并在您找到热点时继续执行您的代码。

类似这样的东西(从概念上讲,需要适当地组织到标题/源中):

struct FunctionTimer {
  FunctionTimer(char const * name) : mName(name), mStartTime(clock()) { }
  ~FunctionTimer() { mFunctionTimes[mName] += clock() - mStartTime; }

  static void report()
  {
    ... iterate through mFunctionTimes, printing out
    the names and accumulated ticks ...
  }

  std::string mName;
  clock_t mStartTime;

  static std::map<std::string, clock_t> mFunctionTimes;
};

...

void myfunc()
{
  FunctionTimer ft("myfunc");
  ... code of myfunc ...
}

...

int main(int argc, char* argv[])
{
  ... do stuff ...
  FunctionTimer::report();
}

【讨论】:

  • 感谢 Scott,替代方法似乎是我能想到的。不幸的是,不是 Valgrind。我会试一试...
【解决方案2】:

一个丑陋的解决方案是围绕每个感兴趣的函数启动和停止计时器,在每次调用后将时间添加到某个全局变量中。然后,在 main 结束时,您只需比较变量即可计算百分比时间。

然而,这可能会变得非常糟糕,尤其是在有很多功能的情况下。如果您熟悉 C++ 的面向方面的风格,您可以暂时使用它,因为方面可以让您更轻松地将样板代码放在所有函数周围。

【讨论】:

    【解决方案3】:

    Wikipedia 维护了一个很好的performance analysis tools for c and c++ 列表,看看它们是否对你有帮助。

    【讨论】:

      猜你喜欢
      • 2012-06-03
      • 1970-01-01
      • 2016-03-08
      • 2011-02-17
      • 2017-07-16
      • 2021-08-31
      • 2017-01-22
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多