Most efficient way to find the greatest of three ints

前端 未结 14 1293
离开以前
离开以前 2020-12-30 07:58

Below is my pseudo code.

function highest(i, j, k)
{
  if(i > j && i > k)
  {
    return i;
  }
  else         


        
14条回答
  •  别那么骄傲
    2020-12-30 08:50

    I like to eliminate conditional jumps as an intellectual exercise. Whether this has any measurable effect on performance I have no idea though :)

    #include 
    #include 
    
    inline int max(int a, int b)
    {
        int difference = a - b;
        int b_greater = difference >> std::numeric_limits::digits;
        return a - (difference & b_greater);
    }
    
    int max(int a, int b, int c)
    {
        return max(max(a, b), c);
    }
    
    int main()
    {
        std::cout << max(1, 2, 3) << std::endl;
        std::cout << max(1, 3, 2) << std::endl;
        std::cout << max(2, 1, 3) << std::endl;
        std::cout << max(2, 3, 1) << std::endl;
        std::cout << max(3, 1, 2) << std::endl;
        std::cout << max(3, 2, 1) << std::endl;
    }
    

    This bit twiddling is just for fun, the cmov solution is probably a lot faster.

提交回复
热议问题