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?
而且,我们可以概括一下,以提高从文件中读取的性能吗?