What is the best (fastest) way to clip a variable using C++ on a modern processor. e.g. If it is below a value, clip it to that value.
I'm aware of a few ways to do it, however, branch prediction comes to mind about the speed. For example:
double ClipValue(double value)
{
if (value < 0)
{
value = 0.0;
}
return value;
}
I would guess that the above would have to branch some of the time.
double ClipValue(double value)
{
return value < 0.0 ? 0.0 : value;
}
This may not.
double ClipValue(double value)
{
return std::max(value, 0.0);
}
And I'm unsure how this would behave.
I guess a lot of it comes down to the compiler and optimizations settings, but what is generally considered the fastest method to saturate a variable. I have used double in this example but I'm equally interested in integers.