使用结构体优化## 结构体成员重排

步骤 1 准备用例

a.c内容:

#include <stdio.h>
#include <stdlib.h>
#include <time.h> 

typedef struct arc
{
 int a;
 double b;
 double c;
 double d;
 short e;
 double f;
 double g;
 double h;
 double i;
} arc_t;
const int MAX = 10000000;
int main ()
{
 arc_t* arcs = (arc_t*) calloc (MAX, sizeof (arc_t));
 time_t start = clock();
 for (int i = 0; i < MAX; i++)
  {   
   arcs[i].a = 1;
   arcs[i].i = 2;
  }
 for (int i = 0; i < MAX; i++)
  {   
   if (arcs[i].a != 1 || arcs[i].i != 2)
    abort();
  }
 time_t end = clock();
 printf("The execution used %f ms.\n", difftime(end, start));
 return 0;
}

步骤 2 对a.c中的结构体类型进行如下修改,并生成b.c:

struct arc
{  
  double b;
  double c;
  double d;  
  double f;
  double g;
  double h;
  double i;
  int a;
  short e;
};

步骤 3 对a.c和b.c进行编译

$ gcc -O3 a.c -o base 
$ gcc -O3 b.c -o test1

步骤 4 执行手动优化结构体的效果:

$ ./base 
The execute used 160.616000 ms.
$ ./test1
The execute used 143.385000 ms.

实验对比手动优化前后的运行时间,从中可以计算出速度比约为1.12(160/143)。

步骤 5 对a.c分别进行开关优化的编译

$ gcc -O3 a.c -o base 
$ gcc -O3 -flto -fwhole-program -flto-partition=one -fipa-reorder-fields a.c -o test2

步骤 6 执行优化查看效果:

$ ./base 
The execute used 161.572000 ms.
$ ./test2
The execute used 145.456000 ms.

从测试用例的运行时间可以看出,通过开启结构体成员重排优化,可以得到和手动优化相似的优化效果。

Logo

openEuler 是由开放原子开源基金会孵化的全场景开源操作系统项目,面向数字基础设施四大核心场景(服务器、云计算、边缘计算、嵌入式),全面支持 ARM、x86、RISC-V、loongArch、PowerPC、SW-64 等多样性计算架构

更多推荐