通过消除对> =比较的需要,将punning带符号的无符号整数类型可以使边界检查更快吗? [英] Could type punning signed to unsigned integers make bounds checking faster by eliminating the need for >= comparison?

查看:73
本文介绍了通过消除对> =比较的需要,将punning带符号的无符号整数类型可以使边界检查更快吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我的程序中有一个非常关键的性能循环,需要检查点是否在矩形内,但是我知道在编译时下界始终为0,如下所示:<代码>(x> = 0& y> = 0&& x<宽度&& y<高度)

Say I had a really performance-critical loop in my program where I need to check if a point was inside a rectangle, but I know at compile time that the lower bounds are always going to be 0, like the following: (x >= 0 && y >= 0 && x < width && y < height)

我可以通过将x和y类型与无符号整数(例如,使用 reinterpret_cast<>() union 类似)来消除前两个比较C ++),因为符号位可以保证任何负数都会变成一个 unsigned int ,其大小足以使边界检查失败?如果是这样,您将如何使用C ++或另一种语言来实现呢?这样可以提高性能吗?

Could I eliminate the first two comparisons by type-punning x and y to unsigned integers (for instance with something like reinterpret_cast<>() or a union in C++), since the sign bit would guarantee any negative number would turn into an unsigned int large enough to fail the bounds check? If so, how would you go about implementing this in C++ or another language? Could you gain any performance improvement by doing this?

推荐答案

是的,当您测试带符号整数且下界为零时,这是一个非常有效的优化.实际上,这是一种常见的优化,编译器几乎可以肯定会自动执行.自己做来使代码模糊不清,这很可能是毫无意义的过早优化.

Yes, it's a perfectly valid optimization when you're testing a signed integer and the lower bound is zero. In fact it's such a common optimization that your compiler will almost certainly do it automatically; obfuscating your code by doing it yourself is very likely to be a pointless premature optimization.

我刚刚在GCC 4.9上对此进行了测试,并通过检查生成的汇编代码来确认它在 -O1 及更高版本中自动执行了此优化.我希望所有现代编译器都能做到这一点.

I just tested this on GCC 4.9, and confirmed by inspecting the generated assembly code that it performs this optimization automatically at -O1 and above. I would expect all modern compilers to do the same.

这篇关于通过消除对&gt; =比较的需要,将punning带符号的无符号整数类型可以使边界检查更快吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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