gpt4 book ai didi

c++ - 如何测量代码片段的调用次数和运行时间

转载 作者:行者123 更新时间:2023-11-27 23:04:29 26 4
gpt4 key购买 nike

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

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

编辑:我在 Windows 7 上工作,但重启到 Ubuntu 应该没有问题(我不熟悉类 unix 操作系统 :( )

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

最佳答案

您正在寻找 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。这里是可执行文件。

正如@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在我的伪网站上找到。

关于c++ - 如何测量代码片段的调用次数和运行时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24576019/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com