C/C ++中的自展开宏循环 [英] Self-unrolling macro loop in C/C++

查看:789
本文介绍了C/C ++中的自展开宏循环的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在从事一个项目,每个周期都很重要.在对我的应用程序进行性能分析时,我发现某些内部循环的开销非常高,因为它们仅包含一些机器指令.此外,这些循环的迭代次数在编译时是已知的.

I am currently working on a project, where every cycle counts. While profiling my application I discovered that the overhead of some inner loop is quite high, because they consist of just a few machine instruction. Additionally the number of iterations in these loops is known at compile time.

因此,我认为不是使用copy&手动展开循环.粘贴,我可以在编译时使用宏展开循环,以便以后可以轻松对其进行修改.

So I thought instead of manually unrolling the loop with copy & paste I could use macros to unroll the loop at compile time so that it can be easily modified later.

我的形象是这样的:

#define LOOP_N_TIMES(N, CODE) <insert magic here>

以便我可以将for (int i = 0; i < N, ++i) { do_stuff(); }替换为:

#define INNER_LOOP_COUNT 4
LOOP_N_TIMES(INNER_LOOP_COUNT, do_stuff();)

它自身展开到:

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

由于大多数时候C预处理器仍然是我的谜,我不知道如何实现此目的,但是我知道这是有可能的,因为Boost似乎有一个BOOST_PP_REPEAT宏.不幸的是,我无法在该项目中使用Boost.

Since the C preprocessor is still a mystery to me most of the time, I have no idea how to accomplish this, but I know it must be possible because Boost seems to have a BOOST_PP_REPEAT macros. Unfortunately I can't use Boost for this project.

推荐答案

您可以使用模板来展开. 请参阅反汇编以获取示例 Live on Godbolt

You can use templates to unroll. See the disassembly for the sample Live on Godbolt

但是 -funroll-loops对于此示例具有相同的效果.

But -funroll-loops has the same effect for this sample.

在Coliru上直播

template <unsigned N> struct faux_unroll {
    template <typename F> static void call(F const& f) {
        f();
        faux_unroll<N-1>::call(f);
    }
};

template <> struct faux_unroll<0u> {
    template <typename F> static void call(F const&) {}
};

#include <iostream>
#include <cstdlib>

int main() {
    srand(time(0));

    double r = 0;
    faux_unroll<10>::call([&] { r += 1.0/rand(); });

    std::cout << r;
}

这篇关于C/C ++中的自展开宏循环的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆