【问题标题】:Loop unrolling in Metal kernels金属内核中的循环展开
【发布时间】:2016-12-20 19:22:29
【问题描述】:

我需要强制 Metal 编译器在我的内核计算函数中展开循环。到目前为止,我尝试将 #pragma unroll(num_times) 放在 for 循环之前,但编译器会忽略该语句。

编译器似乎不会自动展开循环 - 我比较了 1) 代码与 for 循环 2) 相同代码但手动展开循环的执行时间。手动展开的版本快 3 倍。

例如:我想从这里开始:

for (int i=0; i<3; i++) {
    do_stuff();
}

到这里:

do_stuff();
do_stuff();
do_stuff();

Metal C++ 语言中是否有类似循环展开的功能?如果是,我怎么可能让编译器知道我想展开循环?

【问题讨论】:

    标签: ios kernel metal loop-unrolling


    【解决方案1】:

    Metal 是 C++11 的子集,您可以尝试使用模板元编程来展开循环。以下是用金属编译的,虽然我没有时间正确测试它:

    template <unsigned N> struct unroll {
    
        template<class F>
        static void call(F f) {
            f();
            unroll<N-1>::call(f);
        }
    };
    
    template <> struct unroll<0u> {
    
        template<class F>
        static void call(F f) {}
    };
    
    kernel void test() {
    
        unroll<3>::call(do_stuff);
    
    }
    

    请让我知道它是否有效!您可能必须向call 添加一些参数才能将参数传递给do_stuff

    另请参阅:Self-unrolling macro loop in C/C++

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-03-01
      • 1970-01-01
      • 2017-03-13
      • 1970-01-01
      • 2019-05-26
      • 1970-01-01
      • 2012-11-07
      相关资源
      最近更新 更多