编译器想做什么

编译器就程序员写的代码变成CPU能理解机器代码。编译器的指令重排指开启编译器优化后,在不影响代码行为的前提下,代码的顺序会发生改变。

编译器的优化,希望将整个函数用最少的时钟周期来实现。

假设有如下场景:假设该架构下,读取指令从发出到实际读取到数据需要等待2个时钟周期,计算c = b * 3需要一个时钟周期。

{
    load a;
    load b;
    c = b * 3;
    use a and c;
}

正常执行的顺序如下:

{
    load instruction for a (cycle 0);
    load instruction for b (cycle 1);
    wait for b's loading (cycle 2);
    wait for b's loading (cycle 3);
    calculate for c using b (cycle 4);
    use a and c (cycle 5);
}

指令重排后:

{
    load instruction for b (cycle 0);
    load instruction for a (cycle 1); --> padding
    (wait for b's loading (cycle 1);)
    wait for b's loading (cycle 2);
    calculate for c using b (cycle 3);
    use a and c (cycle 4);
}

可以看出,打乱执行顺序之后,节约了一个时钟周期。


最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。