c++ - 基于条件然后三元运算符获取值的更快方法?

标签 c++ c optimization

这就是我想要实现的目标。这很简单:

unsigned int foo1(bool cond, unsigned int num)
{
    return cond ? num : 0;
}

组装:

    test    dil, dil
    mov     eax, 0
    cmovne  eax, esi
    ret

我的问题是,有没有更快的方法呢?以下是我想到的一些方法:

使用乘法:

unsigned int foo2(bool cond, unsigned int num)
{
    return cond * num;
}

组装:

    movzx   eax, dil
    imul    eax, esi
    ret

使用内存访问:

unsigned int foo3(bool cond, unsigned int num)
{
    static const unsigned int masks[2] = { 0x0, 0xFFFFFFFF };
    return masks[cond] & num;
}

程序集:

    movzx   edi, dil
    mov     eax, DWORD PTR foo3(bool, unsigned int)::masks[0+rdi*4]
    and     eax, esi
    ret

使用一些小技巧:

unsigned int foo4(bool cond, unsigned int num) 
{
    return (0 - (unsigned)cond) & num;
}

程序集:

    movzx   eax, dil
    neg     eax
    and     eax, esi
    ret

现在,乘法产生最少的指令,我认为这是最好的选择,但我不确定 imul。有什么建议吗?

提前致谢

最佳答案

乘法和内存访问通常比简单的 if 语句花费更多的时间。如果要优化此代码,最好的方法是仅使用“and”或“or”指令(将其设置为内联以避免顺便调用函数)。

这是使用掩码而不是 bool 值的“优化”函数示例:

inline unsigned int foo1(unsigned int mask, unsigned int num)
{
  return mask & num;
}

你的电话看起来像这样:

foo1(0, 10);     /* Returns 0  */
foo1(~0, 10);    /* Returns 10 */

关于c++ - 基于条件然后三元运算符获取值的更快方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40672821/

相关文章:

c++ - 指向引用的指针是非法的

c++ - 命令行错误 D8003 : missing source filename When linking

c++ - Boost ICL,区间集的基数

c - 公历。如何查找星期一?

c++ - 专门研究 std::vector 如何增长

条件运算符 "? : "

c++ - 在文件开头添加数据

optimization - 如何加速 GLPK 求解 MIP 模型

iphone - 使用 Core Data 会加速键值解析吗?

python - PyGMO Batch 适应性评估