GCC阵列优化

时间:2018-11-27 23:29:00

标签: c arrays gcc compiler-optimization

我有一个仅具有main()的进程和一个几乎为空的查找表:

    int arr[10] = {0, 0, 0, 0, 1, 0, 0, 1, 0, 0};

当我将此数组放在main()之外的全局区域中并用gcc -O2 file.c进行编译时,我得到以下可执行文件:

    bash# size a.out
       text    data     bss     dec     hex filename
       1135     616       8    1759     6df a.out

当我将此数组放入main()函数并用gcc -O2 file.c进行编译时,我得到以下可执行文件:

    bash# size a.out
       text    data     bss     dec     hex filename
       1135     560       8    1703     6a7 a.out

然后,在不修改内容的情况下,将数组的大小更改为10000,然后再次运行测试。这次的结果是:

main()外部:

    bash# size a.out
       text    data     bss     dec     hex filename
       1135   40576       8   41719    a2f7 a.out

在main()内部:

    bash# size a.out
       text    data     bss     dec     hex filename
       1135     560       8    1703     6a7 a.out

当阵列位于全局区域中时,为什么优化不起作用。 有没有一种方法可以在全局区域中保留一个大为空的大型查找表,并对其进行优化?

1 个答案:

答案 0 :(得分:1)

/*have it start emtpy so it can go into .bss*/
int arr[10000];

//__attribute__((constructor))
void arr__init(void)
{
    //set the ones
    arr[4]=1; arr[7]=1; 
}

int main()
{
    //call the initializer
    //(or uncomment the constructor attr to have it called before main automatically (nonstandard))
    arr__init();
    return arr[4]+arr[7]+arr[2];
}

size调用目标文件:

text       data     bss     dec     hex filename
148       0   40000   40148    9cd4 a.out