本文只是一个CUDA编程小白记录学习过程的。更全面的理解和学习请跳转链接
一些前置知识的参考链接:
线程束分化
bank conflict
本文主要学习以下手段对cuda代码进行优化:
- 解决warp divergence
- 解决bank conflict
- 解决idle线程
reduce实现向量元素累加
下面的程序实现一个kernel函数,通过reduce方法实现向量的累加和。代码采用多block实现的,每次调用kernel函数只计算blocksize个元素的累加和。
#include <stdio.h>
#include <cuda_runtime.h>
#include "nvToolsExt.h"
#define THREAD_PER_BLOCK 256
#define N 2048
__host__ void initialData(float *h_a, int n)
{
for(int i = 0; i < n; i++)
{
h_a[i] = 1.0;
//printf("h_a=%f\n", h_a[i]);
}
}
__global__ void reduce0(float *d_in,float *d_out){
__shared__ float sdata[THREAD_PER_BLOCK];
//each thread loads one element from global memory to shared mem
unsigned int i=blockIdx.x*blockDim.x+threadIdx.x;
unsigned int tid=threadIdx.x;
sdata[tid]=d_in[i];
__syncthreads();
// do reduction in shared mem
for(unsigned int s=1; s<blockDim.x; s*=2){
if(tid%(2*s) == 0)