2016-05-17 22 views
1

我想问下我的代码:(下面的代码基本上读取了一个名为inputVelocity.dat的输入文件,其格式为代码中所示的格式。每个值传递给每一个特定的阵列)左右读书20000行时ifstream,getline和istringstream在C++中的大文件上的性能下降

std::ifstream inputVelocity("input/inputVelocity.dat"); 
std::string lineInputVelocity; 
while (std::getline(inputVelocity, lineInputVelocity)) { 
    std::istringstream issVelocity(lineInputVelocity); 
    double a, b, c, d, e; 

    if (!(issVelocity >> a >> b >> c >> d >> e)) { 
    std::cout << "ISS ERROR" << std::endl; 
    } 

    for (int k=0; k<=nz+1; k++) { 
    for (int j=0; j<=ny+1; j++) { 
     for (int i=0; i<=nx+1; i++) { 
     ux[i][j][k]  = a; 
     uy[i][j][k]  = b; 
     uz[i][j][k]  = c; 
     pressure[i][j][k] = d; 
     temperature[i][j][k] = e; 
     } 
    } 
    } 
} 

inputVelocity.close(); 

的代码是好的,但是当我改变文件到大约160万行,代码甚至在服务器上运行很慢。

我在每个getline循环上都执行了std :: cout,它的读取像5行/秒,大约有160万行。

我在这里发现了一些相关的问题,但仍不明白什么是问题来源以及如何解决它。任何人都可以帮忙 谢谢。

+0

首先,你确定你想为每行调用三个'for'循环吗?你知道你的加载程序有复杂度O(行数x NX x NY x NZ)吗? – AnatolyS

+0

@AnatolyS所以你的意思是这样的?我如何改进代码?因为我的所有变量都是三维向量。 – mfakhrusy

+0

我无法理解你在while循环内正在做什么。试着向你解释你想做什么。 – AnatolyS

回答

0

我改变了代码到这一点:

std::ifstream inputVelocity("input/inputVelocity.dat"); 
std::string lineInputVelocity; 
int getI, getJ, getK; 
getI = 0; 
getJ = 0; 
getK = 0; 
while (std::getline(inputVelocity, lineInputVelocity)) { 
    std::istringstream issVelocity(lineInputVelocity); 
    double a, b, c, d, e; 

    if (!(issVelocity >> a >> b >> c >> d >> e)) { 
    std::cout << "ISS ERROR" << std::endl; 
    } 
    std::cout << getI << " " << getJ << " " << getK << std::endl; 
    ux[getI][getJ][getK]    = a; 
    uy[getI][getJ][getK]    = b; 
    uz[getI][getJ][getK]    = c; 
    pressure[getI][getJ][getK]  = d; 
    temperature[getI][getJ][getK]  = e; 

    getK = getK + 1; 

    if (getK == nz+2) { 
    getJ = getJ + 1; 
    getK = 0; 
    } 

    if (getJ == ny+2) { 
    getI = getI + 1; 
    getJ = 0; 
    } 

} 

inputVelocity.close(); 

这真的很好:) 如果任何人有一个更有效的解决方案,我会很高兴地看到! :)