提问者:小点点

如何提高文件读取速度?


我正在读取一个大约包含170万行的txt文件,其中每行由3个整数组成。 我面临的问题是,在向量中循环和存储整数大约需要30秒。

下面是我编写的代码:

std::ifstream finVertices("Phantom Data/FA_vertices.txt", std::ios::in);
    if (!finVertices)
    {
        std::cerr << "Can not open verticies.txt" << std::endl;
    }

    std::cout << "Loading verticies" << std::endl;

    std::string verticesLineBuffer;
    while (std::getline(finVertices, verticesLineBuffer))
    {
        std::istringstream voxelStringCoordinates(verticesLineBuffer);
        GLfloat x, y, z;
        voxelStringCoordinates >> x >> y >> z;
        vertices.push_back(glm::vec3(y, z, x));
    }

    finVertices.close();

txt文件内容示例:

297 13 164
297 13 165
297 14 164
297 14 165
298 13 164
298 13 165

问题:如何改进从txt文件读取的过程?


共1个答案

匿名用户

1)一次读取更大的数据块。比如1MIB或10MIB,或者一次性读取整个文件。然后从读取文件(或数据块)的内存中处理数据。

2)在添加到顶点向量之前,对它调用reserve(),以减少它必须进行的分配数量。

3)在启用优化的情况下编译代码(又称版本构建)