2016-09-25 99 views
0

當我嘗試將一些字符串寫入文件時,我注意到使用ostringstream可以提高性能。C++ ostringstream提高IO性能?

下面的代碼做以下事情:
1.產生一些隨機字符串
2.寫入到一個文件中使用ostringstream
3.寫入到一個文件中使用的ofstream

#include <vector> 
#include <sstream> 
#include <fstream> 
#include <iostream> 
#include <sys/time.h> 

using namespace std; 

double timeGetTimeOfDay(){ 
    struct timeval t; 
    gettimeofday(&t, NULL); 
    return double(t.tv_sec) + double(t.tv_usec)/1000000; 
} 

string genRandString(int length){ 
    string r; 
    for(int i=0; i<length; i++) 
     r.push_back(char('a' + rand()%26)); 
    return r; 
} 

void genRandStrings(vector<string>& allStrings, int count, int length){ 
    srand(unsigned(time(NULL))); 
    for(int i=0; i<count; i++) 
     allStrings.push_back(genRandString(length)); 
} 

int main(){ 
    ofstream fout("temp"); 

    vector<string> allStrings; 
    genRandStrings(allStrings, 100000, 100); 

    // output method1 
    double start = timeGetTimeOfDay(); 
    ostringstream os; 
    for(int i=0; i<allStrings.size(); i++) 
     os<<allStrings[i]<<endl; 
    fout<<os.str(); 
    double end = timeGetTimeOfDay(); 
    cout<<end - start<<endl; 

    // output method2 
    start = timeGetTimeOfDay(); 
    for(int i=0; i<allStrings.size(); i++) 
     fout<<allStrings[i]<<endl; 
    end = timeGetTimeOfDay(); 
    cout<<end - start<<endl; 

    fout.close(); 
    return 0; 
} 

在我的電腦,ostringstream使用0.016933秒,但使用0.132003秒

我不知道爲什麼會發生這種情況?
是否因爲使用ostringstream減少了IO的數量?
std :: ofstream是否有一個緩衝區來減少IO的數量?或者我們每次使用fout<<這將是一個IO?
而且,我們可以概括一下,以提高從文件中讀取的性能嗎?

回答

2

第二種方法由於std :: endl(放置換行符並刷新流)而失敗了內部緩衝區。

通過用\n替換std :: endl並在寫入所有數據後刷新流,第二種方法變得比第一種更快(字符串流成爲額外開銷)。

0.025744 
0.0173609 
:我的系統上

int main(){ 

    vector<string> allStrings; 
    genRandStrings(allStrings, 100000, 100); 

    // output method1 
    { 
     ofstream fout("temp1");      // Distinct output file 
     double start = timeGetTimeOfDay(); 
     ostringstream os; 
     for(unsigned i=0; i<allStrings.size(); i++) 
      os<<allStrings[i]<<'\n';     // New line, only 
     fout << os.str(); 
     fout.flush();         // Flushing output 
     double end = timeGetTimeOfDay(); 
     cout<<end - start<<endl; 
    } 

    // output method2 
    { 
     ofstream fout("temp2");      // Distinct output file 
     double start = timeGetTimeOfDay(); 
     for(unsigned i=0; i<allStrings.size(); i++) 
      fout<<allStrings[i]<<'\n';    // New line, only 
     fout.flush();         // Flushing output 
     double end = timeGetTimeOfDay(); 
     cout<<end - start<<endl; 
    } 
    return 0; 
} 

結果與克++ -std = C++ 14 -O3編譯