2

我用 C 编写了一些代码来读取包含复数的二进制文件。它有效,但我对我需要执行的演员阵容感到不舒服。有没有更好的办法?速度在我的程序中至关重要(我通过将代码从 C++ iostreams 更改为 C stdio 函数,使执行时间加倍)。也可以做得更快吗?

这是我的代码:

#include<complex.h>
#include<errno.h>

#define spaceh 6912
#define Nc 3
#define dirac 4

...  ...

typedef double complex dcomplex;

long size;
size_t result;

char filename[84];
char* buffer;
dcomplex* zbuff;

int i, j, k, srccol, srcdir;
srcdir = 1;
srccol = 2;

/* allocate array dcomplex QM[dirac][Nc][space] on the heap */

sprintf(filename, "/<path>/file.%d.%d.bin", srcdir, srccol);

FILE* input;
input = fopen(filename, "rb");

if(readfile)
{
    fseek(input, 0, SEEK_END);
    size = ftell(input);
    rewind(input);

    buffer = (char*)malloc(sizeof(char)*size);
    if(buffer == NULL)
    {
        fputs("Buffer allocation failed.", stderr);
        exit(1);
    }

    result = fread(buffer, 1, size, input);
    if(result != size)
    {
        fputs("File reading failed.", stderr);
        exit(2);
    }

    /* The cast I'm referring to */
    zbuff = (dcomplex*)buffer;
}
else
{
    printf("File was not successfully opened: %s\n", strerror(errno));
}

count = 0;
for(k = 0; k < space; k++)
{
    for(j = 0; j < Nc; j++)
    {
        for(i = 0; i < dirac; i++)
        {
            QM[i][j][k] = convert_complex(zbuff(count));
            count++;
        }
    }
}

free(buffer);
fclose(input);

convert_complex 函数反转单个复数的字节顺序。我对此更不舒服,但我不希望我的问题变得太大。

4

1 回答 1

2

直接声明zbuff,不需要中间buffer。为此,您将需要在适当的位置进行以下更改。在 fread 中,不是读取大小 1,而是读取 sizeof(dcomplex)。这应该这样做。

    //buffer = (char*)malloc(sizeof(char)*size);
    zbuff = (dcomplex*)malloc(sizeof(dcomplex)*size);
    if(zbuff == NULL)
    {
        fputs("Buffer allocation failed.", stderr);
        exit(1);
    }

    result = fread(zbuff, sizeof(dcomplex), size, input);
    if(result != size)
    {
        fputs("File reading failed.", stderr);
        exit(2);
    }

    /* The cast I'm referring to */
    //zbuff = (dcomplex*)buffer;

    .......

    free(zbuff);

用“zbuff”替换所有出现的“buffer”。

于 2011-02-06T23:01:07.600 回答