Most efficient/elegant way to clip a number?

前端 未结 11 772
予麋鹿
予麋鹿 2020-11-30 03:09

Given a real (n), a maximum value this real can be (upper), and a minimum value this real can be (lower), how can we most efficiently clip n, such that it remains between lo

11条回答
  •  感动是毒
    2020-11-30 03:23

    the best is clearly

    template 
    t clamp2(t x, t min, t max)
    {
    if (x < min) x = min;
    if (x > max) x = max;
    return x;
    }
    

    as it compiles to

    movss   xmm0, cs:__real@c2c80000
    maxss   xmm0, [rsp+38h+var_18]
    movss   xmm1, cs:__real@42c80000
    minss   xmm1, xmm0
    movss   [rsp+38h+var_18], xmm1
    

    it has 0 branches and should be the fastest of all posted above.

    also msvc141 with the standard release settings

提交回复
热议问题