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()?
Asked
Active
Viewed 756 times
1 Answers
3
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);
}
}

Community
- 1
- 1

Robert Crovella
- 143,785
- 11
- 213
- 257
-
Why a macro rather than a function call? – einpoklum Apr 29 '13 at 16:24
-
There's no particular reason. You can easily make a function call version of it. I edited the answer with an example that is created as a function instead of a macro. – Robert Crovella Apr 29 '13 at 17:00