1

我是一个初学者,为了好玩而编写了以下程序,以搜索目录并将每个出现的单词替换为另一个单词。我调用了一次 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() );
}
4

1 回答 1

1

在我的系统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
于 2010-05-07T07:07:48.250 回答