目前,我的代码就是这样:
void ReadFile(double Cst[][1000], char* FileName, int height)
FILE* ifp;
double value;
int nRead = 0;
int mRead = 0;
//open the file, check if successful
ifp = fopen( FileName, "r" );
if (ifp==NULL){
...
}
for (nRead = 0; nRead < height; nRead++){
for (mRead = 0; mRead < 1000; mRead++){
fscanf(ifp, "%le",&value);
Cst[nRead][mRead]=value;
}
}
fclose(ifp);
Run Code Online (Sandbox Code Playgroud)
我可以改变什么来使它尽可能快?
我一直在使用std::atollfrom cstdlib将字符串转换为int64_t带有gcc 的字符串.该工具似乎在Windows工具链上不可用(使用Visual Studio Express 2010).什么是最好的选择?
我也有兴趣转换strings成uint64_t.整数定义取自cstdint.
此函数从字符串中读取双精度数组:
vector<double> parseVals(string& str) {
stringstream ss(str);
vector<double> vals;
double val;
while (ss >> val) vals.push_back(val);
return vals;
}
Run Code Online (Sandbox Code Playgroud)
当使用包含100万个数字的字符串调用时,该函数需要7.8秒才能执行(Core i5,3.3GHz).这意味着花费25000个CPU周期来解析一个NUMBER.
user315052已经指出相同的代码在他的系统上运行速度快了一个数量级,并且进一步的测试显示了不同系统和编译器之间的非常大的性能差异(另见user315052的答案):
1. Win7, Visual Studio 2012RC or Intel C++ 2013 beta: 7.8 sec
2. Win7, mingw / g++ 4.5.2 : 4 sec
3. Win7, Visual Studio 2010 : 0.94 sec
4. Ubuntu 12.04, g++ 4.7 : 0.65 sec
Run Code Online (Sandbox Code Playgroud)
我在Boost/Spirit库中找到了一个很好的选择.代码安全,简洁,速度极快(VC2012上为0.06秒,比stringstream快130倍).
#include <boost/spirit/include/qi.hpp>
namespace qi = boost::spirit::qi;
namespace ascii = boost::spirit::ascii;
vector<double> parseVals4(string& str) {
vector<double> vals;
qi::phrase_parse(str.begin(), str.end(),
*qi::double_ >> …Run Code Online (Sandbox Code Playgroud) 我的问题是关于6502发布的解决方案[ c ++ stringstream太慢,如何加速? 他发布的解析Float方法很快,但是它没有给出大的double值的正确结果.
输入:
132.12345645645645
输出:
132.123
double parseFloat(const std::string& input){
const char *p = input.c_str();
if (!*p || *p == '?')
return NAN_D;
int s = 1;
while (*p == ' ') p++;
if (*p == '-') {
s = -1; p++;
}
double acc = 0;
while (*p >= '0' && *p <= '9')
acc = acc * 10 + *p++ - '0';
if (*p == '.') {
double k = 0.1;
p++;
while …Run Code Online (Sandbox Code Playgroud)