Is there a CUDA equivalent of perror()?

痴心易碎 提交于 2019-12-11 07:11:40

问题


Is there a CUDA function for printing both a caller-supplied error message, and an error message describing the current cudaStatus (or a caller-supplied cudaStatus), a-la-perror()?


回答1:


I don't think there is a built-in cuda API function to do this.

This macro will do what you're describing:

#define cudaCheckErrors(msg) \
    do { \
        cudaError_t __err = cudaGetLastError(); \
        if (__err != cudaSuccess) { \
            fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", \
                msg, cudaGetErrorString(__err), \
                __FILE__, __LINE__); \
            fprintf(stderr, "*** FAILED - ABORTING\n"); \
            exit(1); \
        } \
    } while (0)

The usage of the above macro is simply to insert it after any cuda API call or any cuda kernel call. It's recommended to insert it after every cuda API call and kernel call, for example:

cudaMemcpy(d_A, A, sizeof(A), cudaMemcpyHostToDevice);
cudaCheckErrors("cudaMemcpy fail");
my_kernel<<<blocks, threads>>>(d_A);
cudaCheckErrors("kernel launch fail");
cudaDeviceSynchronize();
cudaCheckErrors("cudaDeviceSynchronize fail");

It prints the user-defined message (msg) and also decodes the cuda API error and prints the appropriate error string message:

Fatal error: kernel launch fail (invalid configuration argument at t128.cu:44)
*** FAILED - ABORTING

You may also be interested in a discussion of error-handling here.

In response to a question below, you can easily make a function-call version:

void cudaCheckErrors(char *msg){
        cudaError_t __err = cudaGetLastError(); \
        if (__err != cudaSuccess) { fprintf(stderr, "Fatal error: %s (%s at %s:%d)\n", msg, cudaGetErrorString(__err),  __FILE__, __LINE__);
            fprintf(stderr, "*** FAILED - ABORTING\n");
            exit(1);
        }
}


来源:https://stackoverflow.com/questions/16282136/is-there-a-cuda-equivalent-of-perror

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!