如何衡量代码片段的通话次数和已用时间

时间:2014-07-04 14:00:35

标签: c++ profiling profiler

当然我有我的源代码,我正在寻找类似QML Profiler(Qt Creator)的东西,但是使用纯C ++代码。我是否必须为此编写自己的代码,或者我可以使用某些工具?

对我来说最重要的是时间&代码中函数的调用次数

编辑:我正在使用Windows 7,但是重启Ubuntu应该没有问题(我不熟悉类Unix操作系统:()

Edit2:我试图找到一些调用图工具,在第一行我会尝试doxygen

2 个答案:

答案 0 :(得分:2)

如果你正在使用GCC,那么你有gprof所有你需要做的就是使用-pg进行编译。还有Google Performance Tools

答案 1 :(得分:2)

您正在寻找CPU分析器。我使用的是GNU gprof

以下是我在link中使用的小指南。

以下是我在代码中从探查器获得的示例输出(在实际运行之前您可以看到),您可以得到您想要的结果:

Flat profile:

Each sample counts as 0.01 seconds.
  %   cumulative   self              self     total           
 time   seconds   seconds    calls  ms/call  ms/call  name    
 52.00      0.13     0.13        5    26.00    26.00  compute_variances(unsigned int, std::vector<float, std::allocator<float> > const&, int, unsigned int const&, float*, float*, unsigned int*)
....
....
 %         the percentage of the total running time of the
time       program used by this function.

cumulative a running sum of the number of seconds accounted
 seconds   for by this function and those listed above it.

 self      the number of seconds accounted for by this
seconds    function alone.  This is the major sort for this
           listing.

calls      the number of times this function was invoked, if
           this function is profiled, else blank.

 self      the average number of milliseconds spent in this
ms/call    function per call, if this function is profiled,
       else blank.

 total     the average number of milliseconds spent in this
ms/call    function and its descendents per call, if this 
       function is profiled, else blank.

name       the name of the function.  This is the minor sort
           for this listing. The index shows the location of
       the function in the gprof listing. If the index is
       in parenthesis it shows where it would appear in
       the gprof listing if it were to be printed.

[编辑]

不要担心Linux! 只需打开一个终端即可(如果你只有一个.cpp文件)

g++ main.cpp -Wall -std=c++0x -p -pg -O3 -o myExe

然后按照我的链接中的步骤操作。

对于更多文件,只需创建一个makefile,如下所示:

sr: main.cpp    polytope.cpp    quadtree.cpp
    g++ -Wextra -Wall -Wreorder -lm -o sr main.cpp polytope.cpp quadtree.cpp    IO.cpp

始终记得在makefile中使用制表符而不是空格。我的makefile太简单了。谷歌搜索可以产生更好的makefile。这是sr可执行文件。

正如@MK所述,在Visual Studio中,您可以使用他们的profiler

[/编辑]

但是,有时候,您只想计算时间。为此你可以这样:

#include <iostream>
#include <ctime>
#include <ratio>
#include <chrono>

int main ()
{
  using namespace std::chrono;

  high_resolution_clock::time_point t1 = high_resolution_clock::now();

  std::cout << "printing out 1000 stars...\n";
  for (int i=0; i<1000; ++i) std::cout << "*";
  std::cout << std::endl;

  high_resolution_clock::time_point t2 = high_resolution_clock::now();

  duration<double> time_span = duration_cast<duration<double>>(t2 - t1);

  std::cout << "It took me " << time_span.count() << " seconds.";
  std::cout << std::endl;

  return 0;
}

或在我的伪网站上找到的任何其他method