CUDA By Example——Julia实例

来源:互联网 发布:java 1 100素数 编辑:程序博客网 时间:2024/04/28 10:30

《CUDA By Example》中文译名《GPU高性能编程CUDA实战》是研究GPGPU异构并行计算非常不错的工具书。因为书中给出的代码,非常个别的地方有失误,而且对不同的编程工具可能需要自己配置链接库。现在我们就跑一下书中第四章Julia的例子,感受一下CUDA的魅力。

1、运行环境

   系统:win10;编程环境:VS2013中文破解版;CUDA版本:CUDA8.0(套件,里面有CUDA驱动,SDK,以及英伟达给的例子)

2、创建CUDA工程

2.1安装完CUDA8.0后VS会自动识别CUDA所以直接打开VS2013就可以创建CUDA工程。




2.2写入代码

创建完工程,把第四章最后完整代码敲入编程工具。完整代码如下:
#include "cuda_runtime.h"#include "device_launch_parameters.h"#include "../common/GL/glut.h"#include "../common/gl_helper.h"#include "../common/cpu_bitmap.h"#include "../common/book.h"#include <stdio.h>using namespace std;#define DIM 1000struct  cuComplex{float r;float i;    __device__ cuComplex(float a, float b){r = a;i = b;}__device__ float magnitude2(void) {    return r * r + i * i;}__device__ cuComplex operator * (const cuComplex& a){return cuComplex(r*a.r - i*a.i, i*a.r + r*a.i);}__device__ cuComplex operator + (const cuComplex& a){return cuComplex(r + a.r, i + a.i);}};    __device__ int julia(int x, int y){const float scale = 1.5;float jx = scale * (float)(DIM / 2 - x) / (DIM / 2);float jy = scale * (float)(DIM / 2 - y) / (DIM / 2);cuComplex c(-0.8, 0.156);cuComplex a(jx, jy);int i = 0;for (i = 0; i < 200; i++){a = a * a + c;if (a.magnitude2() > 1000)return 0;}return 1;}__global__ void kernel(unsigned char *ptr){int x = blockIdx.x;int y = blockIdx.y;int offset = x + y * gridDim.x;int juliaValue = julia(x, y);ptr[offset * 4 + 0] = 255 * juliaValue;ptr[offset * 4 + 1] = 0;ptr[offset * 4 + 2] = 0;ptr[offset * 4 + 3] = 255;}struct DataBlock {unsigned char   *dev_bitmap;};int main(void){CPUBitmap bitmap(DIM, DIM);unsigned char *dev_bitmap;HANDLE_ERROR(cudaMalloc((void**)&dev_bitmap, bitmap.image_size()));dim3 grid(DIM, DIM);kernel<<<grid,1>>>(dev_bitmap);HANDLE_ERROR(cudaMemcpy(bitmap.get_ptr(),dev_bitmap,bitmap.image_size(),cudaMemcpyDeviceToHost));bitmap.display_and_exit();HANDLE_ERROR(cudaFree(dev_bitmap));}

这里要特别说明一下:
  1、CUDA5.0以后英伟达对CUDA库做了较大调整,参看早期教材代码在8.0上运行可能会有问题特别是错误检查的头文件"cutil.h",CUDA5.0以后就不再使用了。
  2、原书中cuComplex类的带参构造函数前没有加__device__是要出错的,这可能是作者的失误。
cuComplex(float a, float b){r = a;i = b;}
改成:
__device__ cuComplex(float a, float b){r = a;i = b;}

2.3配置头文件

如果你以为到这里就可以运行代码那就大错特错了。因为里面有一些作者自己写的头文件(如:book.h)需要加入。这些头文件都可以在CSDN上下载得到,然后按你引入头文件的路径复制到你的工程中。我的工程目录如下:







2.4配置链接库

   如果你的VS安装过程中已经自动安装必备的动态连接库则,配置完头文件后就可以运行了。如果出现连接错误,那么恭喜你中奖了,你有要学会掌握配置动态连接库。
   需要的文件:
    

需要把.lib文件放入VS2013安装路径lib文件夹下:


将.dll文件放入系统盘Windows目录下的两个文件内,根据系统位数的不同放在不同文件夹下(为了更好的兼容性,建议两个文件夹下都放一份)


3、实验结果

到目前为止我们才完成了整个项目的工作。最后运行代码会看到下面漂亮的图片:



0 0
原创粉丝点击