我的 cpp 代码需要读取由空格分隔的浮点值组成的 7 MB 文本文件。将字符串值解析为浮点数组大约需要 6 秒,这对我的用例来说太多了。
我一直在网上查,人们说通常是物理 IO 需要时间。为了消除这种情况,我一次性将文件读入字符串流,并将其用于浮点解析。代码速度仍然没有提高。任何想法如何让它运行得更快?
这是我的代码(为简单起见,用 dummy_f 替换了数组条目):
#include "stdafx.h"
#include <iostream>
#include <fstream>
#include "time.h"
#include <sstream>
using namespace std;
int main()
{
ifstream testfile;
string filename = "test_file.txt";
testfile.open(filename.c_str());
stringstream string_stream;
string_stream << testfile.rdbuf();
testfile.close();
clock_t begin = clock();
float dummy_f;
cout<<"started stream at time "<<(double) (clock() - begin) /(double) CLOCKS_PER_SEC<<endl;
for(int t = 0; t < 6375; t++)
{
string_stream >> dummy_f;
for(int t1 = 0; t1 < 120; t1++)
{
string_stream >> dummy_f;
}
}
cout<<"finished stream at time "<<(double) (clock() - begin) /(double) CLOCKS_PER_SEC<<endl;
string_stream.str("");
return 0;
}
编辑:
这是 test_cases.txt 文件的链接https://drive.google.com/file/d/0BzHKbgLzf282N0NBamZ1VW5QeFE/view?usp=sharing
使用此文件运行时,请将内循环尺寸更改为 128(打错了)
编辑:找到了一种让它工作的方法。将 dummy_f 声明为字符串并从字符串流中读取为字符串单词。然后使用 atof 将字符串转换为浮点数。花费的时间是 0.4 秒,这对我来说已经足够了。
string dummy_f;
vector<float> my_vector;
for(int t = 0; t < 6375; t++)
{
string_stream >> dummy_f;
my_vector.push_back(atof(dummy_f.c_str()));
for(int t1 = 0; t1 < 128; t1++)
{
string_stream >> dummy_f;
my_vector.push_back(atof(dummy_f.c_str()));
}
}