数据读取性能优化

时间:2014-11-03 06:55:16

标签: c endianness

目标是一次从一个文件中读取一个RECORD。每条记录为16个字节。下面的代码一次从文件中读取一个ELEMENT。如何更改fread()以一次读取所有16个字节?

目标:一次从磁盘读取一条记录(在单个fread()调用中从磁盘写入16个字节),然后将其拆分为单个元素。

//Original unoptimized code to read one ELEMENT at a time
// Read the file in a naive way:
// One data item at a time!
struct record read_record_naive(FILE *fp, int endian)
{
  struct record my_data = {0,0,0,0,0};
  int result;
  uint8_t empty=0;

  my_data.valid = 1;
  result = fread(&(my_data.my8), sizeof(my_data.my8), 1, fp);
  if(!result)
    {
      my_data.valid = 0;
      return my_data;
    }

  result = fread(&(empty), sizeof(empty), 1, fp);
  if(!result)
    {
      my_data.valid = 0;
      return my_data;
    }

  result = fread(&(my_data.my16), sizeof(my_data.my16), 1, fp);
  if(!result)
    {
      my_data.valid = 0;
      return my_data;
    }

  result = fread(&(my_data.my32), sizeof(my_data.my32), 1, fp);
  if(!result)
    {
      my_data.valid = 0;
      return my_data;
    }

  result = fread(&(my_data.my64), sizeof(my_data.my64), 1, fp);
  if(!result)
    {
      my_data.valid = 0;
      return my_data;
    }

  if(endian == ENDIAN_LITTLE)
    record_swap_endian(&my_data);

  return my_data;
}

1 个答案:

答案 0 :(得分:1)

简单地说:

result = fread(&my_data), sizeof(my_data), 1, fp);

这还不够吗?