gpt4 book ai didi

c++ - 从 istringstream 读取比 ifstream 慢

转载 作者:行者123 更新时间:2023-11-28 01:28:13 27 4
gpt4 key购买 nike

我正在尝试读取点云文件 (PTX)。为此,我尝试了 2 种解决方案:

第一种:最简单的方法。 std::ifstreamgetline(...) 我可以阅读。
第二个:我读取所有内容并将所有内容放入 std::istringstream 然后使用 operator >> 从中读取。
因为我用第二种方法把所有东西都放在内存中,所以我想从中读取会更快但没有。
平均:方法 1 为 45 秒,方法 2 为 49 秒。

这是我的代码:
方法一:

std::istringstream getLine(std::ifstream& file) {
std::string line;
std::getline(file, line);
return std::istringstream{ line };
}

void readPoint(std::ifstream& file, TinyPTX& tptx) {
std::vector<PointPTX> ptxPoints(tptx.numPoints);

size_t num_pts_to_remove = 0;
tptx.asCol = true;
for (int i = 0; i < tptx.numPoints; ++i) {
float x, y, z, intens;
uint8_t r, g, b;
getLine(file) >> x >> y >> z >> intens >> r >> g >> b;
PointPTX& _pptx = tptx.cloud->points[i - num_pts_to_remove];
if (!isZero(x, 10e-4) || !isZero(y, 10e-4) || !isZero(z, 10e-4)) {
_pptx.x = x; _pptx.y = y; _pptx.z = z; _pptx.intensity = intens;
_pptx.r = r;
_pptx.g = g;
_pptx.b = b;
}
else
num_pts_to_remove++;
}
tptx.numPoints -= num_pts_to_remove;
tptx.cloud->points.resize(tptx.numPoints);
}

方法二:

bool readPoint(std::istringstream& str, TinyPTX& tptx, std::streamsize& size) {
std::vector<PointPTX> ptxPoints(tptx.numPoints);

size_t num_pts_to_remove = 0;
for (int i = 0; i < tptx.numPoints; ++i) {
float x, y, z, intens;
int r, g, b;
str >> x >> y >> z >> intens >> r >> g >> b;
PointPTX& _pptx = tptx.cloud->points[i - num_pts_to_remove];
if (!isZero(x, 10e-4) || !isZero(y, 10e-4) || !isZero(z, 10e-4)) {
_pptx.x = x; _pptx.y = y; _pptx.z = z; _pptx.intensity = intens;
_pptx.r = r;
_pptx.g = g;
_pptx.b = b;
}
else
num_pts_to_remove++;
}
tptx.numPoints -= num_pts_to_remove;
tptx.cloud->points.resize(tptx.numPoints);

int pos = str.tellg();
std::cout << pos << " " << size;
return pos > size - 10 ;//Used to know if we're at the end of the file.
}

我的问题是:为什么我将所有内容都放入内存的版本比另一个版本慢?有什么我想念的吗?我做错了吗?

最佳答案

Is there something I'm missing? I'm doing wrong?

如果您想忽略该行的其余部分,则只有为每一行创建一个中间 std::istringstream 才有意义。

如果所有行仅包含这 7 个值,您可以直接从 std::istream& file(而不是 std::ifstream& file)读取它们。 IE。改变:

getLine(file) >> x >> y >> z >> intens >> r >> g >> b;

到:

file >> x >> y >> z >> intens >> r >> g >> b;

关于c++ - 从 istringstream 读取比 ifstream 慢,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52854366/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com