gpt4 book ai didi

c - 如何优化 C 中围绕零对称的整数区间的范围检查?

转载 作者:太空狗 更新时间:2023-10-29 17:04:42 26 4
gpt4 key购买 nike

有什么方法可以优化以下 C 代码行(以避免分支)?

if (i < -threshold || i > threshold) { 
counter++;
}

所有变量都是 16 位有符号整数。优化后的版本应该具有高度可移植性。

最佳答案

以下情况如何:

counter += (i < -threshold) | (i > threshold);

假设原始代码是有效的,那么这应该也可以以可移植的方式工作。该标准表示关系运算符( <> 等)返回 int。等于 1成功,或 0失败时。

更新

要回答 Sheen 下面的评论,请使用以下代码:

int main()
{
short threshold = 10;
short i = 20;
short counter = 0;

counter += (i < -threshold) | (i > threshold);

return 0;
}

在没有优化的情况下使用 GCC 在 x86 上产生以下反汇编程序:

  push   %rbp
mov %rsp,%rbp
movw $0xa,-6(%rbp)
movw $0x14,-4(%rbp)
movw $0x0,-2(%rbp)
movswl -4(%rbp),%edx
movswl -6(%rbp),%eax
neg %eax
cmp %eax,%edx
setl %dl
movzwl -4(%rbp),%eax
cmp -6(%rbp),%ax
setg %al
or %edx,%eax
movzbw %al,%dx
movzwl -2(%rbp),%eax
lea (%rdx,%rax,1),%eax
mov %ax,-2(%rbp)
mov $0x0,%eax
leaveq
retq

关于c - 如何优化 C 中围绕零对称的整数区间的范围检查?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4034542/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com