gpt4 book ai didi

c++ - 为什么 gprof 告诉我从 main() 只调用一次的函数被调用了 102 次?

转载 作者:太空宇宙 更新时间:2023-11-04 12:25:26 24 4
gpt4 key购买 nike

我是初学者,为了好玩而编写了以下程序,用于搜索目录并将每个出现的单词替换为另一个单词。我只调用了一次 crt_ls_file() 函数,但 gprof 告诉我它被调用了 102 次。我想知道是否有人知道这是为什么。我试过编译程序,但没有优化。

#include <iostream>
#include <string>
#include <cstdlib>
#include <cassert>
#include <fstream>
using namespace std;

void crt_ls_file(const string& output_f, const string& dir);
void sed(const string& old_string, const string& new_string, const string& filename, const string& directory);

int main(int argc, char* argv[]){

string out_f;
if (argc <= 1) {
cout << "Usage: " << argv[0] << " <Filename>" << endl;
exit(EXIT_FAILURE);
} else {
out_f = ".sandr";
crt_ls_file(out_f, string(argv[1]) );
}

ifstream out_fs( out_f.c_str() );
string line;
getline(out_fs, line);
while( !out_fs.eof() ){
sed(string("index_SYMBOL"), string("index1_SYMBOL"), line, string(argv[1]) );
getline(out_fs, line);
}
out_fs.close();
string f( "rm " + out_f );
system ( f.c_str() );

exit(EXIT_SUCCESS);
}

void crt_ls_file(const string& s, const string& a){
ofstream ls( s.c_str() );
ls.close();
string ls_output( "ls -1 " + a + " > ./" + string(s) );
system( ls_output.c_str() );
}

void sed(const string& o, const string& n, const string& f, const string& d){
ofstream dummy(".temp");
dummy.close();

string sed_output( "sed 's/" + o + "/" + n + "/g' " + d + "/" + f + " > .temp" );
system( sed_output.c_str() );
string rp( "mv .temp " + d + "/" + f );
system ( rp.c_str() );
}

最佳答案

在我的系统上,gprof 只显示了一次对 crt_ls_file 的调用,它应该是这样的:

  0.00      0.00     0.00        1     0.00     0.00  crt_ls_file(std::string const&, std::string const&)

看来您 gprof 在撒谎,有时确实如此。如果你真的想分析这个程序(用处不大),试试 callgrind 和 kcachegrind。它们是更好且不那么神秘的工具:

$ valgrind --tool=callgrind ./my_program some_dir
... let it do its job ...
$ kcachegrind

关于c++ - 为什么 gprof 告诉我从 main() 只调用一次的函数被调用了 102 次?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2786785/

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