手机版
你好,游客 登录 注册
背景:
阅读新闻

Ubuntu 12.04 下 CUDA 编程

GPU 程序加速(4)

[日期:2014-06-12] 来源:Linux社区  作者:xsc_c [字体:大 中 小]

3、线程同步和共享内存

前面的程序,计算求和的工作在 CPU 中完成,总共需要在 CPU 中做 512 次加法运算,那么有没有办法减少 CPU 中执行加法的次数呢???

可以通过同步和共享内存技术,实现在 GPU 上的 block 块内求取部分和,这样最后只需要在 CPU 计算 16 个和就可以了。具体实现方法如下:

首先,在修改内核函数,定义一块共享内存,用 __shared__ 指示:

__global__ static void squaresSum(int *data, int *sum, clock_t *time)
{
 __shared__ int shared[BLOCK_NUM];
 const int tid = threadIdx.x;
 const int bid = blockIdx.x;

 if (tid == 0) time[bid] = clock();

 shared[tid] = 0;

 for (int i = bid * THREAD_NUM + tid; i < DATA_SIZE; i += BLOCK_NUM * THREAD_NUM) {
  shared[tid] += data[i] * data[i];
 }

 __syncthreads();
 if (tid == 0) {
  for (int i = 1; i < THREAD_NUM; i++) {
   shared[0] += shared[i];
  }
  sum[bid] = shared[0];
 }

 if (tid == 0) time[bid + BLOCK_NUM] = clock();
}

利用 __shared__ 声明的变量是 shared memory,每个 block 中,各个 thread 之间对于共享内存是共享的,利用的是 GPU 上的内存,所以速度很快,不必担心 latency 的问题。

__syncthreads() 函数是 CUDA 的内部函数,表示所有 threads 都必须同步到这个点,才会执行接下来的代码。我们要做的就是等待每个 thread 计算结束以后,再来计算部分和,所以同步是必不可少的环节。把每个 block 的部分和计算到 shared[0] 里面。

接着,修改主函数部分:

int main(int argc, char const *argv[])
{
 // init CUDA device
 if (!InitCUDA()) {
  return 0;
 }
 printf("CUDA initialized.\n");

 // generate rand datas
 generateData(data, DATA_SIZE);

 // malloc space for datas in GPU
 int *gpuData, *sum;
 clock_t *time;
 cudaMalloc((void**) &gpuData, sizeof(int) * DATA_SIZE);
 <strong>cudaMalloc((void**) &sum, sizeof(int) * BLOCK_NUM);</strong>
 cudaMalloc((void**) &time, sizeof(clock_t) * BLOCK_NUM * 2);
 cudaMemcpy(gpuData, data, sizeof(int) * DATA_SIZE, cudaMemcpyHostToDevice);

 // calculate the squares's sum
 <strong>squaresSum<<<BLOCK_NUM, THREAD_NUM, THREAD_NUM * sizeof(int)>>>(gpuData, sum, time);</strong>

 // copy the result from GPU to HOST
 int result[BLOCK_NUM];
 clock_t time_used[BLOCK_NUM * 2];
 cudaMemcpy(&result, sum, sizeof(int) * BLOCK_NUM, cudaMemcpyDeviceToHost);
 cudaMemcpy(&time_used, time, sizeof(clock_t) * BLOCK_NUM * 2, cudaMemcpyDeviceToHost);

 // free GPU spaces
 cudaFree(gpuData);
 cudaFree(sum);
 cudaFree(time);

 // print result
 int tmp_result = 0;
 for (int i = 0; i < <strong>BLOCK_NUM</strong>; ++i) {
  tmp_result += result[i];
 }

 clock_t min_start, max_end;
 min_start = time_used[0];
 max_end = time_used[BLOCK_NUM];
 for (int i = 1; i < BLOCK_NUM; ++i) {
  if (min_start > time_used[i]) min_start = time_used[i];
  if (max_end < time_used[i + BLOCK_NUM]) max_end = time_used[i + BLOCK_NUM];
 }
 printf("(GPU) sum:%d time:%ld\n", tmp_result, max_end - min_start);

 // CPU calculate
 tmp_result = 0;

 for (int i = 0; i < DATA_SIZE; ++i) {
  tmp_result += data[i] * data[i];
 }

 printf("(CPU) sum:%d\n", tmp_result);

 return 0;
}

相对与前一个版本,只需要修改 sum 数组的大小,以及调用核函数的代码。

编译运行代码,结果如下:

Ubuntu 12.04 下 CUDA 编程

jping@CJP-PC:~/cuda/2.0_SquareSum$ ./squareSum&nbsp;
CUDA initialized.
(GPU) sum:29909398 time:1812756
(CPU) sum:29909398
jping@CJP-PC:~/cuda/2.0_SquareSum$&nbsp;

其实和前一版程序相比,时间上没有什么优势,原因在于,我们需要在 GPU 中额外运行求和的这部分代码,导致了运行周期的变长,不过相应的,在 CPU 中的运行时间会减少。

我们在这个程序中,只当每个 block 的 thread0 的时候,计算求和的工作,这样做影响了执行的效率,其实求和可以并行化处理的,也就是通过加法树来实现并行化。举个例子,要计算 8 个数的和,我们没必要用一个 for 循环,逐个相加,而是可以通过第一级流水线实现两两相加,变成 4 个数,第二级流水实现两两相加,变成 2 个数,第三级流水实现两两相加,求得最后的和。

下面通过加法树的方法,实现最后的求和,修改内核函数如下:

__global__ static void squaresSum(int *data, int *sum, clock_t *time)
{
 __shared__ int shared[BLOCK_NUM];
 const int tid = threadIdx.x;
 const int bid = blockIdx.x;

 int offset = THREAD_NUM / 2;

 if (tid == 0) time[bid] = clock();

 shared[tid] = 0;

 for (int i = bid * THREAD_NUM + tid; i < DATA_SIZE; i += BLOCK_NUM * THREAD_NUM) {
  shared[tid] += data[i] * data[i];
 }

 __syncthreads();
 while (offset > 0) {
  if (tid < offset) {
   shared[tid] += shared[tid + offset];
  }
  offset >>= 1;
  __syncthreads();
 }

 if (tid == 0) {
  sum[bid] = shared[0];
  time[bid + BLOCK_NUM] = clock();
 }
}

此程序实现的就是上诉描述的加法树的结构,注意这里第二个 __syncthreads() 的使用,也就是说,要进行下一级流水线的计算,必须建立在前一级必须已经计算完毕的情况下。

主函数部分不许要修改,最后编译运行结果如下:

Ubuntu 12.04 下 CUDA 编程

jping@CJP-PC:~/cuda/2.0_SquareSum$ ./squareSum
CUDA initialized.
(GPU) sum:29909398 time:1799680
(CPU) sum:29909398
jping@CJP-PC:~/cuda/2.0_SquareSum$

性能有一部分的改善。

通过使用 GPU 的并行化编程,确实对性能会有很大程度上的提升。由于受限于 Geforce 103m 的内存带宽,程序只能优化到这一步,关于是否还有其他的方式优化,有待进一步学习。

最后给出最终的代码:

/* *******************************************************************
##### File Name: squareSum.cu
##### File Func: calculate the sum of inputs's square
##### Author: Caijinping
##### E-mail: caijinping220@gmail.com
##### Create Time: 2014-5-7
* ********************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>

// ======== define area ========
#define DATA_SIZE 1048576 // 1M
#define BLOCK_NUM 8   // block num
#define THREAD_NUM 64  // thread num

// ======== global area ========
int data[DATA_SIZE];

void printDeviceProp(const cudaDeviceProp &prop);
bool InitCUDA();
void generateData(int *data, int size);
__global__ static void squaresSum(int *data, int *sum, clock_t *time);

int main(int argc, char const *argv[])
{
 // init CUDA device
 if (!InitCUDA()) {
  return 0;
 }
 printf("CUDA initialized.\n");

 // generate rand datas
 generateData(data, DATA_SIZE);

 // malloc space for datas in GPU
 int *gpuData, *sum;
 clock_t *time;
 cudaMalloc((void**) &gpuData, sizeof(int) * DATA_SIZE);
 cudaMalloc((void**) &sum, sizeof(int) * BLOCK_NUM);
 cudaMalloc((void**) &time, sizeof(clock_t) * BLOCK_NUM * 2);
 cudaMemcpy(gpuData, data, sizeof(int) * DATA_SIZE, cudaMemcpyHostToDevice);

 // calculate the squares's sum
 squaresSum<<<BLOCK_NUM, THREAD_NUM, THREAD_NUM * sizeof(int)>>>(gpuData, sum, time);

 // copy the result from GPU to HOST
 int result[BLOCK_NUM];
 clock_t time_used[BLOCK_NUM * 2];
 cudaMemcpy(&result, sum, sizeof(int) * BLOCK_NUM, cudaMemcpyDeviceToHost);
 cudaMemcpy(&time_used, time, sizeof(clock_t) * BLOCK_NUM * 2, cudaMemcpyDeviceToHost);

 // free GPU spaces
 cudaFree(gpuData);
 cudaFree(sum);
 cudaFree(time);

 // print result
 int tmp_result = 0;
 for (int i = 0; i < BLOCK_NUM; ++i) {
  tmp_result += result[i];
 }

 clock_t min_start, max_end;
 min_start = time_used[0];
 max_end = time_used[BLOCK_NUM];
 for (int i = 1; i < BLOCK_NUM; ++i) {
  if (min_start > time_used[i]) min_start = time_used[i];
  if (max_end < time_used[i + BLOCK_NUM]) max_end = time_used[i + BLOCK_NUM];
 }
 printf("(GPU) sum:%d time:%ld\n", tmp_result, max_end - min_start);

 // CPU calculate
 tmp_result = 0;

 for (int i = 0; i < DATA_SIZE; ++i) {
  tmp_result += data[i] * data[i];
 }

 printf("(CPU) sum:%d\n", tmp_result);

 return 0;
}

__global__ static void squaresSum(int *data, int *sum, clock_t *time)
{
 __shared__ int shared[BLOCK_NUM];
 const int tid = threadIdx.x;
 const int bid = blockIdx.x;

 int offset = THREAD_NUM / 2;

 if (tid == 0) time[bid] = clock();

 shared[tid] = 0;

 for (int i = bid * THREAD_NUM + tid; i < DATA_SIZE; i += BLOCK_NUM * THREAD_NUM) {
  shared[tid] += data[i] * data[i];
 }

 __syncthreads();
 while (offset > 0) {
  if (tid < offset) {
   shared[tid] += shared[tid + offset];
  }
  offset >>= 1;
  __syncthreads();
 }

 if (tid == 0) {
  sum[bid] = shared[0];
  time[bid + BLOCK_NUM] = clock();
 }
}

// ======== used to generate rand datas ========
void generateData(int *data, int size)
{
 for (int i = 0; i < size; ++i) {
  data[i] = rand() % 10;
 }
}


void printDeviceProp(const cudaDeviceProp &prop)
{
 printf("Device Name : %s.\n", prop.name);
 printf("totalGlobalMem : %d.\n", prop.totalGlobalMem);
 printf("sharedMemPerBlock : %d.\n", prop.sharedMemPerBlock);
 printf("regsPerBlock : %d.\n", prop.regsPerBlock);
 printf("warpSize : %d.\n", prop.warpSize);
 printf("memPitch : %d.\n", prop.memPitch);
 printf("maxThreadsPerBlock : %d.\n", prop.maxThreadsPerBlock);
 printf("maxThreadsDim[0 - 2] : %d %d %d.\n", prop.maxThreadsDim[0], prop.maxThreadsDim[1], prop.maxThreadsDim[2]);
 printf("maxGridSize[0 - 2] : %d %d %d.\n", prop.maxGridSize[0], prop.maxGridSize[1], prop.maxGridSize[2]);
 printf("totalConstMem : %d.\n", prop.totalConstMem);
 printf("major.minor : %d.%d.\n", prop.major, prop.minor);
 printf("clockRate : %d.\n", prop.clockRate);
 printf("textureAlignment : %d.\n", prop.textureAlignment);
 printf("deviceOverlap : %d.\n", prop.deviceOverlap);
 printf("multiProcessorCount : %d.\n", prop.multiProcessorCount);
}

bool InitCUDA()
{
 //used to count the device numbers
 int count; 

 // get the cuda device count
 cudaGetDeviceCount(&count);
 if (count == 0) {
  fprintf(stderr, "There is no device.\n");
  return false;
 }

 // find the device >= 1.X
 int i;
 for (i = 0; i < count; ++i) {
  cudaDeviceProp prop;
  if (cudaGetDeviceProperties(&prop, i) == cudaSuccess) {
   if (prop.major >= 1) {
    //printDeviceProp(prop);
    break;
   }
  }
 }

 // if can't find the device
 if (i == count) {
  fprintf(stderr, "There is no device supporting CUDA 1.x.\n");
  return false;
 }

 // set cuda device
 cudaSetDevice(i);

 return true;
}

更多Ubuntu相关信息见Ubuntu 专题页面 http://www.linuxidc.com/topicnews.aspx?tid=2

本文永久更新链接地址:http://www.linuxidc.com/Linux/2014-06/103056.htm

linux
【内容导航】
第1页:GPU 运行程序(1) 第2页:GPU 运行程序(2)
第3页:GPU 运行程序(3) 第4页:GPU 程序加速(1)
第5页:GPU 程序加速(2) 第6页:GPU 程序加速(3)
第7页:GPU 程序加速(4)
本文评论   查看全部评论 (0)
表情: 表情 姓名: 字数

       

评论声明
  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款