Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
1–10 of 152 posts
Re: Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
#2Re: Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
#3Re: Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
#4Always specify your target.
Re: Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
#5Both recent GCC and Clang are able to generate the most optimal version for std::clamp() if you add something like -march=znver1, even at -O1 [0]. Interesting! [0] https://godbolt.org/z/YsMMo7Kjz
When AVX isn’t enabled, the std::min + std::max example still uses fewer instructions. Looks like a random register allocation failure.
Re: Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
#6Re: Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
#7If you benchmark these, you'll likely find the version with the jump edges out the one with the conditional instruction in practice.
Re: Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
#8I'm a heavy std::clamp user, but I'm considering replacing it with min+max because of the uncertainty about what will happen when lo > hi. On windows it triggers an assertion, while other platforms just do a min+max in one or the other order. Of course, this should never happen but can be difficult to guarantee when the limits are derived from user inputs.
Re: Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
#9Both recent GCC and Clang are able to generate the most optimal version for std::clamp() if you add something like -march=znver1, even at -O1 [0]. Interesting! [0] https://godbolt.org/z/YsMMo7Kjz
But then it uses AVX instructions. (You can replace -march=znver1 with just -mavx.) When AVX isn’t enabled, the std::min + std::max example still uses fewer instructions. Looks like a random register allocation failure.
Re: Std: Clamp generates less efficient assembly than std:min(max,std:max(min,v))
#10https://gcc.godbolt.org/z/fGaP6roe9
I see the same behavior on clang 17 as well