performance of unsigned vs signed integers(无符号与有符号整数的性能)
问题描述
使用无符号整数而不是有符号整数是否有任何性能增益/损失?
Is there any performance gain/loss by using unsigned integers over signed integers?
如果是这样,这是否也适用于短期和长期?
If so, does this goes for short and long as well?
推荐答案
使用 unsigned int 除以 2 的幂更快,因为它可以优化为单个移位指令.对于 signed int,它通常需要更多的机器指令,因为除法 向零舍入,但向右移动 向下.示例:
Division by powers of 2 is faster with unsigned int, because it can be optimized into a single shift instruction. With signed int, it usually requires more machine instructions, because division rounds towards zero, but shifting to the right rounds down. Example:
int foo(int x, unsigned y)
{
x /= 8;
y /= 8;
return x + y;
}
这里是相关的 x 部分(签名除法):
Here is the relevant x part (signed division):
movl 8(%ebp), %eax
leal 7(%eax), %edx
testl %eax, %eax
cmovs %edx, %eax
sarl $3, %eax
这里是相关的 y 部分(无符号除法):
And here is the relevant y part (unsigned division):
movl 12(%ebp), %edx
shrl $3, %edx
这篇关于无符号与有符号整数的性能的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:无符号与有符号整数的性能
基础教程推荐
- 为什么我们不能使用“虚拟继承"?在 COM 中? 2022-01-01
- 将不可复制的闭包对象传递给 std::function 参数 2021-01-01
- 随机插入/删除的综合向量与链表基准 2022-01-01
- 如何部分禁用 cmake C/C++ 自定义编译器检查 2021-01-01
- 与 CAS 的原子交换(使用 gcc 同步内置函数) 2022-01-01
- 如何更改 SysDateTimePick32 或 CDateTimeCtrl 的背景颜色? 2022-01-01
- 提升 ASIO 流缓冲 2021-01-01
- C++:获取传递给函数的多维数组的行大小 2021-01-01
- c++ STL设置差异 2022-01-01
- 如何在 C++ 中正确使用命名空间? 2022-01-01
