【发布时间】:2020-06-16 02:21:35
【问题描述】:
我正在读取一个包含大约 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 文件的读取过程?
编辑:感谢您的帮助。在您的帮助下,我设法解决了这个问题。 代码如下:
std::ifstream is(fileName, std::ifstream::binary);
if (is) {
is.seekg(0, is.end);
int length = is.tellg();
is.seekg(0, is.beg);
char* buffer = new char[length];
is.read(buffer, length);
is.close();
for (unsigned int i = 0; i < is.gcount(); i++)
{
// here can get access to each indiviual character
}
【问题讨论】:
-
push_back可能是您的问题的一部分。如果您知道在创建向量时保留了多少验证。 -
vertices是否有足够的保留大小,因此不必重新分配? -
iostreams是效率低下的模型。当速度很重要时,您不想使用iostreams或std::strings。我会使用mmap将整个文件映射到内存中,然后对其进行迭代,使用std::from_chars逐个删除整数值。 -
为什么使用字符串流而不是直接从文件中读取?
-
正如 Jesper 指出的,您的构建设置在这里很重要。那些是什么?你能增加优化吗?
标签: c++