2010-05-07 66 views
1

我是一個初學者,爲了好玩寫了下面的程序,搜索一個目錄並用一個詞替換每個詞的每一個出現。我一次調用crt_ls_file()函數,一次,但gprof告訴我它被調用了102次。我想知道是否有人知道這是爲什麼。我已經嘗試編譯該程序將全部並沒有優化。爲什麼gprof告訴我一個從main()被調用一次的函數被稱爲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()); 
} 

回答

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 
相關問題