CUDA resource management with error detection

        Many cuda codes are found to be redundant in the project, mainly because there are some cuda memory-related operations, such as after cudaMemcpy, error detection is required, so a version has been modified to implement internal detection of the interface, so that the code does not look so messy.

        Why use macro definitions instead of function definitions? Because of function definitions, if you want to directly output the file and line number of the error location when an error occurs, you need to pass __FILE__ and __LINE__ when using the interface. It is a bit troublesome to enter, so the way of macro definition is used

The following is the specific code:

        

#pragma once
#include <assert.h>
#include <cuda_runtime.h>
#include <string>

// 向上取整
#define iDIV_UP(a, b) ((a + b - 1) / b)
#define ALG_MAX(x,y) ((x)>(y)?(x):(y))
#define ALG_MIN(x,y) ((x)<(y)?(x):(y))
#define FLOAT_EPS  1e-6
#define FLOAT_EQUAL(v1, v2) ((fabs((v1)-(v2))) < (FLOAT_EPS))

// cblas错误检查
#define CheckCBlasError(ErrorID)        \
{                                       \
    if(CUBLAS_STATUS_SUCCESS != ErrorID)\
    {                                   \
        printf("=====Imaging Error CBlas: %s, line: %d of file: %s\n", cublasGetStatusString(ErrorID), __LINE__, __FILE__);\
        assert(false);                  \
    }                                   \
}

#define CheckCudaError(ErrorId){\
    if (cudaSuccess != ErrorId)\
    { \
        printf("=====Imaging Error Cuda: %s, file: %s : %d\n", cudaGetErrorString(ErrorId), __FILE__, __LINE__);assert(false);\
    }\
}

// Cuda显存释放
#define Cuda_Free(pData){ \
    if (nullptr != pData){\
        cudaError_t error_id = cudaFree(pData);\
        pData = nullptr;\
        CheckCudaError(error_id);\
    }\
}

// Cuda显存设置值
#define Cuda_Memset(devPtr, iValue, iSize){\
    void** ptr = (void**)&devPtr;\
    if (ptr != nullptr){\
        auto error_id = cudaMemset(*ptr, iValue, iSize);\
        CheckCudaError(error_id);\
    }\
}

// 显存申请
#define Cuda_Malloc(pData, iSize){\
    Cuda_Free(*pData);\
    cudaError_t error_id = cudaMalloc(pData, iSize);\
    CheckCudaError(error_id);\
}


#define Cuda_Memcpy(pDst, pSrc, iSize, cpyKind){\
    auto error_id = cudaMemcpy(pDst, pSrc, iSize, cpyKind);\
    CheckCudaError(error_id);\
}

Guess you like

Origin blog.csdn.net/bocai1215/article/details/130328727