gpt4 book ai didi

c++ - 从不遵循计算机字节对齐的 HDD 读取文件时出现性能问题

转载 作者:太空宇宙 更新时间:2023-11-04 15:53:32 28 4
gpt4 key购买 nike

我有一个使用 50 字节数据结构的文件格式(.STL,立体光刻,结构是标准的,不能更改。不要与标准模板库混淆)。直接从硬盘读取会导致读取错误数据,因为50字节不是4的倍数。

在整个 50 字节的结构中,我只需要其中的 36 个字节。我现在使用的提取数据的方法是手动将文件的读取位置偏移到下一组数据开始的位置,将36字节读取到一个临时变量中,然后将数据转储到临时变量中到它在阵列上的适当位置。

这是代码块:

threePoints* output = new threePoints [numTriangles]; // create an array to hold the entire file
threePoints* temp = new threePoints [1]; // temp variable to pull data out of each "cell"

// extract each triangle individualy
for (int i = 0; i < numTriangles; i++)
{
stlFile.seekg (96 + i * 50, ios::beg); //read vertex data and put them into tempoary array
// offset = 80 header + 4 #triangles + 12 normal vector
stlFile.read(reinterpret_cast<char*>(temp), (36)); // read the next 36 data blocks into holder, 3 points * 3 axis * 4 bytes per float
output[i] = temp[0]; // dump values in holder into proper array
}

此方法有效但速度较慢。我该怎么做才能让它更快、更高效?

编辑:我知道手动禁用字节对齐可以解决这个问题,但我需要大量使用生成的数组并多次迭代它。有人告诉我禁用字节对齐会导致性能问题,因此我避免了它。

最佳答案

与其进行一堆小的查找和读取,不如分配一个大缓冲区(比如,足以容纳 1000 个结构)并一次读取一堆记录。 (然后遍历该缓冲区,复制出您需要的 36 字节 block )。

关于c++ - 从不遵循计算机字节对齐的 HDD 读取文件时出现性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3824703/

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