max( a, b ) ( ((a) > (b)) ? (a) : (b) ) in cuda? how to use above c function in cuda

#ifndef max
#define max( a, b ) ( ((a) > (b)) ? (a) : (b) )

#ifndef min
#define min( a, b ) ( ((a) < (b)) ? (a) : (b) )

In C, I have defined these two small functions and use quite often.
now when it comes to CUDA, I just notice that I need to do convert the function in CUDA form.

Is there any simple way to do it? or callable function ?

Just let me know where to look or terms that I have to search…

Thanks in advance and any help is appreciated.

can i just use (((a)<(b))?(a):(b)) or (((a)>(b))?(a):(b)) in CUDA instead of min(a,b) or max(a,b)?

in other words, can i use (? :) in cuda?

You can use defines like that the same way as in C.

And yes you can use (?:) constructs.



Thanks for the quick reply.

well, it seems like i have a problem…

when i modified the sample like the following, suddenly it complains

“fatal error LNK1181: cannot open input file ‘’”

(i build up my own cuda stuffs in the same file and without new additions, no problem at all)

i also get error as soon as i replaced all min()/max() with (?:) statements…

am i missing calling some .h files?

i am already calling

#include <stdio.h>

#include <math.h>

thanks again.

#define SDATA( index) cutilBankChecker(sdata, index)

#ifndef max

#define max( a, b ) ( ((a) > (b)) ? (a) : (b) )


#ifndef min

#define min( a, b ) ( ((a) < (b)) ? (a) : (b) )


CUDA already supports min() and max() functions. These are overloaded functions with support for a large number of types, so there should be no need to define macros for this purpose. Note that functions are safer than macros for this purpose since the arguments are not evaluated twice. In addition to overloaded min() and max() there are also the C99-compatible math functions fmin(), fmax(), fminf(), fmaxf() for floating-point data.

hmmm. surprise.

a regular min/max returns the smaller/greater of two arguments, i think.

in my case, there is ‘if’ decision (? :) is involved.

max(a,b) == (((a)>(b))?(a):(b))

are you saying CUDA supported min/max is doing the same ?

The CUDA versions do the same, except that they are superior because cover all the intrinsic types CUDA supports and compile to a single PTX instruction without any conditional execution.

Does the conditional operator (?:) cause warp divergence? Thanks!

Yes it does. That may or may not be important. Most uses of the ? operator are trivial, so don’t worry about it… only larger functions of meaty branches really matter for thread divergence.

So you could create a bad example like

y=   (x>10) ? Bigfunction1(x) : OtherFunction2(x);

But that’s a pretty rare use of the ? operator. Just think of the equivalent if statement, the generated code is almost always identical or nearly so.