cuda::clamp#
Defined in the <cuda/cmath> header.
namespace cuda {
template <typename T>
[[nodiscard]] __host__ __device__ constexpr
T clamp(T value, T low, T high) noexcept;
} // namespace cuda
The function clamps value to the range [low, high], computed as cuda::max(cuda::min(value, high), low).
Contrary to cuda::std::clamp, which takes its arguments by reference and returns a reference to one of them, the function takes and returns values. This lets the compiler compute the result in registers, instead of selecting the address of an argument and loading the result from it.
For floating-point types, NaN values are handled like with cuda::min and cuda::max.
Parameters
value: The value to clamp.low: The lower boundary.high: The upper boundary.
Return value
lowifvalueis less thanlow,highifhighis less thanvalue, otherwisevalue.For floating-point types, a NaN boundary is ignored. If
valueis NaN, the result ishigh, orlowifhighis NaN as well.
Constraints
Tis an arithmetic type or an extended floating-point type.
Preconditions
highis not less thanlow.
Performance considerations
On device, the function maps to a
minand amaxptx instruction for integer types of up to 64 bits andfloat, fordoubleon GPUs with fast FP64 arithmetic, and for__halfand__nv_bfloat16onSM80and newer. On GPUs with slow FP64 arithmetic,doublevalues are compared with integer ptx instructions instead.
Example#
#include <cuda/cmath>
#include <cuda/std/cassert>
__global__ void kernel()
{
assert(cuda::clamp(-1, 0, 3) == 0);
assert(cuda::clamp(2, 0, 3) == 2);
assert(cuda::clamp(5, 0, 3) == 3);
}
int main()
{
kernel<<<1, 1>>>();
cudaDeviceSynchronize();
}