我有1GB的二进制文件,它基本上包含相同类型值的3D立方体.使用不同的顺序([x,y,z]或[zx,y])保存这种多维数据集需要花费大量时间来使用fseek和fwrite.但其中一个软件包比我的程序快得多.是否有任何方法使文件写入比使用fseek/fwrite更快?
你不应该在文件io操作的内部循环中使用fseek.为了使写入功能更快,它们会缓存写入.如果你到处寻找,你一直在吹缓存.
在内存中完成所有转换 - 例如在内存中旋转多维数据集,然后在几个后续的fwrite调用中写入文件.
如果你无法在内存中完全转换数据,那么在内存中一次将一个平面组装成一个平面并写出每个平面.
@编辑:
在你的情况下,你根本不想使用fseek.甚至没有一个.
做这样的事情:
void writeCubeZYX( int* cubeXYZ, int sizeOfCubeXYZ, FILE* file )
{
int* cubeZYX = malloc( sizeOfCubeXYZ );
// all that monkey business you're doing with fseek is done inside this
// function copying memory to memory. No file IO operations in here.
transformCubeXYZ_to_ZYX( cubeXYZ, cubeZYX, sizeOfCubeXYZ );
// one big fat very fast fwrite. Optimal use of file io cache.
fwrite( file, cubeZYX, 1, sizeOfCubeXYZ );
free( cubeZYX ); // quiet pedantry.
}
Run Code Online (Sandbox Code Playgroud)
@ EDIT2:
好吧,假设您无法在内存中对其进行全部转换,然后在平面中对其进行转换并一次写出一个平面 - 按文件顺序 - 没有fseeks.
所以说[XYZ]立方体在内存中被布置为一系列Z [XY]矩阵.也就是说,你的立方体的[XY]平面在内存中是连续的.你想写出[ZYX].所以在文件中你要写出一系列X [ZY]矩阵.每个[ZY]在文件中都是连续的.
所以你做这样的事情:
void writeCubeZYX( int* cubeXYZ, int x, int y, int z, FILE* file )
{
int sizeOfPlaneZY = sizeof( int ) * y * z;
int* planeZY = malloc( sizeOfPlaneZY );
for ( int i = 0; i < X; i++ )
{
// all that monkey business you're doing with fseek is done inside this
// function extracting one ZY plane at a time. No file IO operations in here.
extractZYPlane_form_CubeXYZ( cubeXYZ, planeZY, i );
// in X big fat very fast fwrites. Near optimal use of file io cache.
fwrite( file, planeZY, 1, sizeOfPlaneZY );
}
free( planeZY ); // quiet pedantry.
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2011 次 |
| 最近记录: |