从HD读取文件而不遵循计算机字节对齐时的性能问题

Fak*_*ken 0 c++ performance file-io

我有一个使用50字节数据结构的文件格式(.STL,立体光刻,结构是标准的,不能更改.不要与标准模板库混淆).从HD读取直接导致读取错误的数据,因为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
}
Run Code Online (Sandbox Code Playgroud)

这种方法有效,但速度很慢.我将如何做到这一点,使其更快,更有效?

编辑:我知道手动禁用字节对齐将解决此问题,但我需要密集使用生成的数组并多次迭代它.我被告知禁用字节对齐会导致性能问题,因此我避免使用它.

Dav*_*har 6

而不是做一堆小的搜索和读取,分配一个大缓冲区(比如足够1000个结构)并一次读取一堆记录.(然后遍历该缓冲区,复制出你需要的36字节块).

  • 好答案.问题不是错位,问题是做了一堆冗余的读请求. (3认同)