CUDA中自动初始化显卡设备宏

每次为了减少初始化的工作量,可以写入下面的宏。

#define CUT_DEVICE_INIT(ARGC,ARGV){    \
    int deviceCount;    \
    CUDA_SAFE_CALL_NO_SYNC(cudaGetDeviceCount(&deviceCount));    \
    if(deviceCount == 0){    \
        fprintf(stderr,"cutil error:no devices supporting CUDA.\n")    \
        exit(EXIT_FAILURE);    \
    }    \
    int dev=0;    \
    cutGetCmdLineArgumenti(ARGC,(const char **) ARGV,"device",&dev);    \
    if(dev < 0) dev=0;    \
    if(dev > deviceCount - 1) dev=deviceCount - 1;    \
    cudaDeviceProp deviceProp;    \
    CUDA_SAFE_CALL_NO_SYNC(cudaGetDeviceProperties(&deviceProp,dev));    \
    if(deviceProp.major < 1){    \
        fprintf(stderr,"cutil error: device does not support CUDA.\n");    \
        exit(EXIT_FAILURE);    \
    }    \
    if(cutCheckCmdLineFlag(ARGC,    (const char **) ARGV,"quiet") == CUTFalse)    \
        fprintf(stderr,"Using device %d:%s\n",dev,deviceProp.name);    \
    CUDA_SAFE_CALL(cudaSetDevice(dev));    \
}

#define CUT_EXIT(argc,argv)    \
    if(!cutCheckCmdLineFlag(argc, ( const char **)argv, "noprompt")){    \
        printf("\n Press ENTER to exit...\n");    \
        fflush(stdout);    \
        fflush(stderr);    \
        
        getchar();    \
    }    \
exit(EXIT_SUCCESS);

在主程序中:

int main(int argc,char** argv){
    CUT_DEVICE_INIT(argc,argv);
    ...主程序内容
    CUT_EXIT(argc,argv);
}

转载于:https://my.oschina.net/u/204616/blog/545284

猜你喜欢

转载自blog.csdn.net/weixin_34018202/article/details/91989963