我对此进行了测试。写信给stringstream
你几乎一无所获。使用FILE *
而不是fstream
确实给出了合理的改进。
这是我的测试代码:
#include <vector>
#include <utility>
#include <fstream>
#include <iostream>
#include <sstream>
#include <cstdio>
using namespace std;
bool printPoints(const vector <pair <double,double> > &points, const string &file)
{
if(points.empty())
return false;
vector <pair <double,double> >::const_iterator i;
if(file != "")
{
stringstream ss;
for(i=points.begin(); i != points.end();++i )
{
ss << i->first << " " << i->second << "\n";
}
ofstream out(file.c_str());
if(out.fail())
{
out.close();
return false;
}
out << ss.str();
out.close();
}
return true;
}
bool printPoints2(const vector <pair <double,double> > &points, const string &file)
{
if(points.empty())
return false;
vector <pair <double,double> >:: const_iterator i;
if(file != "")
{
ofstream out(file.c_str());
if(out.fail())
{
out.close();
return false;
}
for(i=points.begin(); i != points.end();++i )
{
out << i->first << " " << i->second << "\n";
}
out.close();
}
return true;
}
bool printPoints3(const vector <pair <double,double> > &points, const string &file)
{
if(points.empty())
return false;
vector <pair <double,double> >:: const_iterator i;
if(file != "")
{
FILE *out = fopen(file.c_str(), "w");
if(!out)
{
return false;
}
for(i=points.begin(); i != points.end();++i )
{
fprintf(out, "%f %f", i->first, i->second);
}
fclose(out);
}
return true;
}
static __inline__ unsigned long long rdtsc(void)
{
unsigned hi, lo;
__asm__ __volatile__ ("rdtsc" : "=a"(lo), "=d"(hi));
return ( (unsigned long long)lo)|( ((unsigned long long)hi)<<32 );
}
int main()
{
vector <pair <double,double> > v;
unsigned long long t1, t2;
for(int i = 1; i <= 10000000; i++)
{
v.push_back(make_pair<double, double>((double)i, 1.0/i));
}
t1 = rdtsc();
printPoints(v, "points.txt");
t2 = rdtsc();
cout << "time = " << t2 - t1 << endl;
t1 = rdtsc();
printPoints2(v, "points2.txt");
t2 = rdtsc();
cout << "time = " << t2 - t1 << endl;
t1 = rdtsc();
printPoints3(v, "points3.txt");
t2 = rdtsc();
cout << "time = " << t2 - t1 << endl;
}
Results:
time = 55363637480
time = 54413392112
time = 33069402767
显然,结果可能会因处理器类型、内存类型、硬盘系统(或网络驱动器存储)等而有所不同。但我过去对此进行了测试,并发现了类似的结果。