CUDA代码常用编写技巧

1.  声明 __shared__ 变量或数组:

 

__shared__   float   sh_farr[  256 ];
__shared__  
int   a;

 

2.结构体指针成员的分配设备内存:

typedef  struct  Teacher_t
{
    
int a;
    unsigned 
int    *g_mem1;
    
float            *g_mem2;
}
Teacher;
void  initMem( Teacher &  t,  const  unsigned  int  mat_size) 
{
    unsigned 
int mat_size_ui = sizeof(int* mat_size;
    unsigned 
int mat_size_f = sizeof(float* mat_size;
    CUDA_SAFE_CALL( cudaMalloc((
void**)&t.g_mem1, mat_size_ui) );
    CUDA_SAFE_CALL( cudaMalloc((
void**)&t.g_mem1, mat_size_f) );
    ...
}

 

3.计时:

unsigned  int  timer  =   0 ;
CUT_SAFE_CALL( cutCreateTimer( 
& timer));
CUT_SAFE_CALL( cutStartTimer( timer));
{
      ...
//kernel
}

CUT_SAFE_CALL( cutStopTimer( timer));
printf( 
" Total time: %f ms  " , cutGetTimerValue( timer)  );
    CUT_SAFE_CALL( cutDeleteTimer( timer));

 

4. 获取输入命令行中包含的文件名:

 

////
// ! Check if a particular filename has to be used for the file where the result
// ! is stored
// ! @param argc  number of command line arguments (from main(argc, argv)
// ! @param argv  pointers to command line arguments (from main(argc, argv)
// ! @param  filename  filename of result file, updated if user specified
// !                   filename
////
void
getResultFilename( 
int  argc,  char **  argv,  char *&  filename) 
{

    
char* temp = NULL;
    cutGetCmdLineArgumentstr( argc, (
const char**) argv, "filename-result", &temp);
    
if( NULL != temp) 
    
{
        filename 
= (char*) malloc( sizeof(char* strlen( temp));
        strcpy( filename, temp);
        cutFree( temp);
    }

    printf( 
"Result filename: '%s' ", filename);
}

类似的:

 

////
// ! Check if a specific precision of the eigenvalue has to be obtained
// ! @param argc  number of command line arguments (from main(argc, argv)
// ! @param argv  pointers to command line arguments (from main(argc, argv)
// ! @param iters_timing  numbers of iterations for timing, updated if a 
// !                      specific number is specified on the command line
////
void
getPrecision( 
int  argc,  char **  argv,  float &  precision)
{
    
float temp = -1.0f;
    cutGetCmdLineArgumentf( argc, (
const char**) argv, "precision"&temp);
    
if( temp > 0.0f
    
{
        precision 
= temp;
    }

    printf( 
"Precision: %f ", precision);
}

 

5.Host调用完kernel函数需要进行线程同步,而在kernel或global函数只需要在必要的地方__syncthreads();即可:

CUDA_SAFE_CALL( cudaThreadSynchronize());

 

 

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值