比如这样一个结构体
#define ATTR_SIZE 50
#define BODY_SIZE 6000
struct LIST_OF_OBJ {
struct LIST_OF_OBJ *next;
int obj_attr[ATTR_SIZE];
int obj_body[BODY_SIZE];
};
如果某些情况下,比如只需遍历使用obj_attr,那么在遍历的时候,obj_body这个巨大的数组也会被加载到内存,然后再加载到CPU的缓存中,但是实际上是不需要的,所以这个加载就浪费了很多的时间。所以可以改成这个样子
#define N_ELEM 10000
#define ATTR_SIZE 50
#define BODY_SIZE 6000
struct LIST_OF_OBJ_OPT {
struct LIST_OF_OBJ_OPT *next;
int obj_attr[ATTR_SIZE];
int *obj_body;//改为指针形式
};
这样的话,访问obj_attr的时候,多余加载进来的就只有四个字节的obj_body,就不会浪费很多的时间了
当然,如果需要计算链表个数,也就是有只访问next的情况,那么obj_attr也可以改成指针的形式。
#include<stdio.h>
#include<stdlib.h>
#include<sys/time.h>
#define N_ELEM 10000
#define ATTR_SIZE 50
#define BODY_SIZE 6000
struct LIST_OF_OBJ {
struct LIST_OF_OBJ *next;
int obj_attr[ATTR_SIZE];
int obj_body[BODY_SIZE];
};
struct LIST_OF_OBJ *list_of_obj, *tmp_list_of_obj;
struct LIST_OF_OBJ_OPT {
struct LIST_OF_OBJ_OPT *next;
int obj_attr[ATTR_SIZE];
int *obj_body;
};
struct LIST_OF_OBJ_OPT *list_of_obj_opt, *tmp_list_of_obj_opt;
void test1()
{
struct timeval start1;
struct timeval end1;
list_of_obj = (struct LIST_OF_OBJ *)malloc(N_ELEM * sizeof(struct LIST_OF_OBJ));
for (int a = 0; a < N_ELEM; a++) {
list_of_obj[a].next = list_of_obj + a + 1;
}
list_of_obj[N_ELEM - 1].next = 0;
for (int i = 0; i < N_ELEM; i++)
{
for (int j = 0; j < ATTR_SIZE; j++)
{
list_of_obj[i].obj_attr[j] = j;
}
}
tmp_list_of_obj = list_of_obj;
gettimeofday(&start1, NULL);
int x = 0;
do {
for (int attr = 0; attr < ATTR_SIZE; attr++)
{
x += tmp_list_of_obj[0].obj_attr[attr];
}
}while(tmp_list_of_obj=tmp_list_of_obj[0].next);
gettimeofday(&end1, NULL);
int speedtime = (end1.tv_sec * 1000000 + end1.tv_usec) - (start1.tv_sec * 1000000 + start1.tv_usec);
printf("%d gettimeofday = %d\n", x, speedtime);
}
void test2()
{
struct timeval start1;
struct timeval end1;
list_of_obj_opt = (struct LIST_OF_OBJ_OPT *)malloc(N_ELEM * sizeof(struct LIST_OF_OBJ_OPT));
for (int a = 0; a < N_ELEM; a++) {
list_of_obj_opt[a].next = list_of_obj_opt + a + 1;
list_of_obj_opt[a].obj_body = (int *)malloc(sizeof(int) * BODY_SIZE);
}
list_of_obj_opt[N_ELEM - 1].next = 0;
for (int i = 0; i < N_ELEM; i++)
{
for (int j = 0; j < ATTR_SIZE; j++)
{
list_of_obj_opt[i].obj_attr[j] = j;
}
}
tmp_list_of_obj_opt = list_of_obj_opt;
gettimeofday(&start1, NULL);
int x = 0;
do {
for (int attr = 0; attr < ATTR_SIZE; attr++)
{
x += tmp_list_of_obj_opt[0].obj_attr[attr];
}
}while(tmp_list_of_obj_opt=tmp_list_of_obj_opt[0].next);
gettimeofday(&end1, NULL);
int speedtime = (end1.tv_sec * 1000000 + end1.tv_usec) - (start1.tv_sec * 1000000 + start1.tv_usec);
printf("%d gettimeofday = %d\n", x, speedtime);
}
int main() {
test1();
test2();
return 0;
}
在ubuntu的测试效果如下:
![](https://img-blog.csdnimg.cn/img_convert/b80525e481f049b295ab65970aafc830.png)