代码之家  ›  专栏  ›  技术社区  ›  R zu

软件预取和反向循环

  •  2
  • R zu  · 技术社区  · 6 年前

    我是否正确地使用了预取指令来减少内存延迟?

    当我用-O3编译代码时,g++似乎展开了内部循环( code at godbolt.org ).

    CPU的体系结构是Broadwell。

    谢谢。


    #include <stdlib.h>
    #include <iostream>
    int main() {
        const int N = 25000000;
        float* x = reinterpret_cast<float*>(
                aligned_alloc(16, 4*N)
        );  // 0.1 GB
    
        x[N - 1] = 1.0f;
    
        // fetch last cache line of the array
        __builtin_prefetch(&x[N - 16], 0, 3);
    
        // Backward loop over the i^th cache line.
        for (int i = N - 16; i >= 0; i -= 16) {
            for (int j = 15; j >= 1; --j) {
                x[i + j - 1] += x[i + j];
            }
            __builtin_prefetch(&x[i - 16], 0, 3);
            x[i - 1] = x[i];
        }
    
        std::cout << x[0] << "\n";
        free(x);
    }
    
    0 回复  |  直到 6 年前