【发布时间】:2013-02-02 22:51:30
【问题描述】:
我的代码将大小大于 1000 万的向量写入文本文件。我使用 clock() 来计时 writefile 函数及其程序中最慢的部分。有没有比我下面的方法更好的写入文件的方法?
void writefile(vector<fields>& fieldsvec, ofstream& sigfile, ofstream& noisefile)
/* Writes clean and noise data to respective files
*
* fieldsvec: vector of clean data
* noisevec: vector of noise data
* sigfile: file to store clean data
* noisefile: file to store noise data
*/
{
for(unsigned int i=0; i<fieldsvec.size(); i++)
{
if(fieldsvec[i].nflag==false)
{
sigfile << fieldsvec[i].timestamp << ";" << fieldsvec[i].price << ";" << fieldsvec[i].units;
sigfile << endl;
}
else
{
noisefile << fieldsvec[i].timestamp << ";" << fieldsvec[i].price << ";" << fieldsvec[i].units;
noisefile << endl;
}
}
}
我的结构在哪里:
struct fields
// Stores a parsed line of a file
{
public:
string timestamp;
float price;
float units;
bool nflag; //flag if noise (TRUE=NOISE)
};
【问题讨论】:
-
你可以回退到 fread/fwrite 的旧 C i/o 函数,看看是否更快?
-
我打赌“fprintf()”会比
ostream快很多——不幸的是,它需要一些重写,使用“FILE *”而不是“ostream&”作为输入函数。