位运算符的位运算速度
假设我有
x &(num-1)
其中 x 是无符号 long long 和 num 常规 int 和 &是按位与运算符。
随着 num 值的增加,我的速度显着降低。这是正常行为吗?
这些是受影响的代码的其他部分
int* hash = new int[num]
Suppose I have
x &(num-1)
where x is an unsigned long long and num a regular int and & is the bitwise and operator.
I'm getting a significant speed reduction as the value of num increases. Is that normal behavior?
These are the other parts of the code that are affected
int* hash = new int[num]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我不认为按位运算正在减慢,我认为您使用它的次数更多了。可能甚至不是按位运算花费的时间太长,而是其他任何事情你也做了更多次。
使用分析器。
I don't think that the bitwise operation is slowing down, I think you're using it a lot more times. And probably it isn't even the bitwise operation that's taking too long, but whatever else you're also doing more times.
Use a profiler.
如果您在紧密循环中执行代码,则完全有可能您会看到性能随着 num 的获取而降低,我猜测您的 C++ 编译器无法找到执行 & 的本机指令带有 unsigned long long - 正如您所说,对于 2 的每个幂,您的速度都会变慢,那么我希望 & 产生的代码会变慢。重复“num”除以 2,直到它为零,并逐位执行“and”。
另一种可能性是,您运行的 CPU 很差劲,无法在固定数量的周期内执行 AND 操作。
If you're executing the code in a tight loop, it's wholly possibly that you'll see the performance lessen the higher num gets, I'm guessing that your C++ compiler isn't able to find a native instruction to perform the & with an unsigned long long - as you've stated your getting a slowdown for each power of two then I'd expect that the code that results from the & is repeatedly "dividing num" by 2 until it's zero and performing the and bit-by-bit.
Another possibility is that the CPU you're running on is lame and doesn't perform AND in a fixed number of cycles.
问题解决了。它与 CPU 缓存和局部性有关。
Problem solved. It had to do with the CPU cache and locality.