检查两个整数是否在0的同一侧的最快方法 [英] Fastest way to check if two integers are on the same side of 0
问题描述
我需要检查两个整数是否在零的同一侧多次。我不在乎它是积极的还是消极的,只是它是同一面......并且表现非常重要。
I need to check if two integers are on the same side of zero many times. I don't care if it's positive or negative, just that it's the same side... and performance is very important.
目前我这样做:
if (int1 == 0 || int2 == 0) {
// handle zero
} else if ((int1 ^ int2) > 0) {
// different side
} else {
// same side
}
速度提高了30%(使用 caliper )更明显:
This is a 30% improvement in speed (tested with caliper) over the more obvious:
if ((int1 > 0 && int2 > 0) || (int1 < 0 && int2 < 0)) {
可以更快地完成吗?
如果有人想要看到我用于30%的测试框架,就在这里。我使用了卡尺0.5-rc1
注意:所有这些解决方案都检查了第一位,基本上,零是与正数相同。因此,如果这适用于您的应用程序,则无需进行零检查。
NOTE: All of these solutions check the first bit, basically, which for zero is the same as a positive number. So if that works for your application, you don't need to do a zero check.
基准列表:
- XOR:错误修正的原始答案
- Ifs:明显
( (&&)||(&&))
解决方案 - 比特: @ hatchet的解决方案
(>> 31)==(>> 31)
- BitAndXor: @ greedybuddha的解决方案
(0x80000000)
- BitAndEquals: @ greedybuddha的解决方案已修改为使用
==
不是^
- XorShift: @ aaronman的解决方案
( ^)>> 31 == 0
- XOR: Original answer with bugfix
- Ifs: Obvious
((&&)||(&&))
solution - Bits: @hatchet's solution
(>>31) == (>>31)
- BitAndXor: @greedybuddha's solution
(0x80000000)
- BitAndEquals: @greedybuddha's solution modified to use
==
not^
- XorShift: @aaronman's solution
(^)>>31 == 0
0% Scenario{vm=java, trial=0, benchmark=XOR} 1372.83 ns; ?=7.16 ns @ 3 trials
17% Scenario{vm=java, trial=0, benchmark=Ifs} 2397.32 ns; ?=16.81 ns @ 3 trials
33% Scenario{vm=java, trial=0, benchmark=Bits} 1311.75 ns; ?=3.04 ns @ 3 trials
50% Scenario{vm=java, trial=0, benchmark=XorShift} 1231.24 ns; ?=12.11 ns @ 5 trials
67% Scenario{vm=java, trial=0, benchmark=BitAndXor} 1446.60 ns; ?=2.28 ns @ 3 trials
83% Scenario{vm=java, trial=0, benchmark=BitAndEquals} 1492.37 ns; ?=14.62 ns @ 3 trials
benchmark us linear runtime
XOR 1.37 =================
Ifs 2.40 ==============================
Bits 1.31 ================
XorShift 1.23 ===============
BitAndXor 1.45 ==================
BitAndEquals 1.49 ==================
vm: java
trial: 0
看起来@aaronman是赢家
Looks like @aaronman is the winner
推荐答案
(int1 ^ int2)>> 31 == 0? / *在同一侧* /:/ *不同的一方* /;
这不一定正确处理0我不确定在这种情况下你想做什么。
编辑:还想指出,如果这是在c而不是java,它可以通过摆脱 == 0
进一步优化,因为布尔值的方式在c中工作,案例将被切换
(int1 ^ int2) >> 31 == 0 ? /*on same side*/ : /*different side*/ ;
This doesn't necessarily handle 0 correctly I'm not sure what you wanted to do in that case.
also wanted to point out that if this was in c instead of java, it could be optimized further by getting rid of the == 0
because of the way that booleans work in c, the cases would be switched though
这篇关于检查两个整数是否在0的同一侧的最快方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!