我可以通过给出整数范围来提示优化器吗? [英] Can I hint the optimizer by giving the range of an integer?

查看:125
本文介绍了我可以通过给出整数范围来提示优化器吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 int 类型来存储值。根据程序的语义,值总是在很小的范围内变化(0 - 36),而 int (不是 char )仅仅因为CPU效率而被使用。

I am using an int type to store a value. By the semantics of the program, the value always varies in a very small range (0 - 36), and int (not a char) is used only because of the CPU efficiency.

似乎可以在如此小的整数范围内执行许多特殊的算术优化。对这些整数的许多函数调用可能会被优化为一小组神奇操作,有些函数甚至可以优化为表格查找。

It seems like many special arithmetical optimizations can be performed on such a small range of integers. Many function calls on those integers might be optimized into a small set of "magical" operations, and some functions may even be optimized into table look-ups.

所以,是有可能告诉编译器这个 int 总是在那么小的范围内,编译器是否可以进行那些优化?

So, is it possible to tell the compiler that this int is always in that small range, and is it possible for the compiler to do those optimizations?

推荐答案

是的,有可能。例如,对于 gcc ,您可以使用 __ builtin_unreachable 告诉编译器有关不可能的条件,例如:

Yes, it is possible. For example, for gcc you can use __builtin_unreachable to tell the compiler about impossible conditions, like so:

if (value < 0 || value > 36) __builtin_unreachable();

我们可以在宏中包含上述条件:

We can wrap the condition above in a macro:

#define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)

并像这样使用它:

assume(x >= 0 && x <= 10);

正如你所看到的 gcc 执行优化对此信息进行了编辑:

As you can see, gcc performs optimizations based on this information:

#define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)

int func(int x){
    assume(x >=0 && x <= 10);

    if (x > 11){
        return 2;
    }
    else{
        return 17;
    }
}

产生:

func(int):
    mov     eax, 17
    ret

然而,有一个缺点是如果你的代码打破了这样的假设,就会得到未定义的行为

即使在调试版本中,它也不会在发生这种情况时通知您。要更容易地调试/测试/捕获错误,你可以使用混合的假设/断言宏(@David Z的积分),如下所示:

It doesn't notify you when this happens, even in debug builds. To debug/test/catch bugs with assumptions more easily, you can use a hybrid assume/assert macro (credits to @David Z), like this one:

#if defined(NDEBUG)
#define assume(cond) do { if (!(cond)) __builtin_unreachable(); } while (0)
#else
#include <cassert>
#define assume(cond) assert(cond)
#endif

In调试版本( NDEBUG 定义),它的工作方式类似于普通的断言,打印错误消息和 abort '程序,在发布版本中,它使用了一个假设,产生了优化的代码。

In debug builds (with NDEBUG not defined), it works like an ordinary assert, printing error message and abort'ing program, and in release builds it makes use of an assumption, producing optimized code.

但请注意,它不能替代常规断言 - cond 仍然在发布版本中,所以你应该不要像那样做(VeryExpensiveComputation())

Note, however, that it is not a substitute for regular assert - cond remains in release builds, so you should not do something like assume(VeryExpensiveComputation()).

这篇关于我可以通过给出整数范围来提示优化器吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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