迈克老狼2012 发表于 2012-10-25 01:16:10

OpenCL 学习step by step (2) 一个简单的OpenCL的程序

OpenCL 学习step by step (2) 一个简单的OpenCL的程序

“      现在,我们开始写一个简单的OpenCL程序,计算两个数组相加的和,放到另一个数组中去。程序用cpu和gpu分别计算,最后验证它们是否相等。OpenCL程序的流程大致如下:

http://images.cnblogs.com/cnblogs_com/mikewolf2002/201209/201209050649037425.png
下面是source code中的主要代码:
 
int main(int argc, char* argv[])      
    {      
    //在host内存中创建三个缓冲区      
    float *buf1 = 0;      
    float *buf2 = 0;      
    float *buf = 0;
    buf1 =(float *)malloc(BUFSIZE * sizeof(float));      
    buf2 =(float *)malloc(BUFSIZE * sizeof(float));      
    buf =(float *)malloc(BUFSIZE * sizeof(float));
    //用一些随机值初始化buf1和buf2的内容      
    int i;      
    srand( (unsigned)time( NULL ) );      
    for(i = 0; i < BUFSIZE; i++)      
        buf1 = rand()%65535;
    srand( (unsigned)time( NULL ) +1000);      
    for(i = 0; i < BUFSIZE; i++)      
        buf2 = rand()%65535;
    //cpu计算buf1,buf2的和      
    for(i = 0; i < BUFSIZE; i++)      
        buf = buf1 + buf2;
    cl_uint status;      
    cl_platform_id platform;
    //创建平台对象      
    status = clGetPlatformIDs( 1, &platform, NULL );
      注意:如果我们系统中安装不止一个opencl平台,比如我的os中,有intel和amd两家opencl平台,用上面这行代码,有可能会出错,因为它得到了intel的opencl平台,而intel的平台只支持cpu,而我们后面的操作都是基于gpu,这时我们可以用下面的代码,得到AMD的opencl平台。      
 
<div style="border-bottom: silver 1px solid; text-align: left; border-left: silver 1px solid; padding-bottom: 4px; line-height: 12pt; background-color: #f4f4f4; margin: 20px 0px 10px; padding-left: 4px; width: 97.5%; padding-right: 4px; font-family: &#39;Courier New&#39;, courier, monospace; direction: ltr; max-height: 200px; font-size: 8pt; overflow: auto; border-top: silver 1px solid; cursor: text; border-right: silver 1px solid; padding-top: 4px" id="codeSnippetWrapper">   cl_uint numPlatforms;
std::string platformVendor;
status = clGetPlatformIDs(0, NULL, &numPlatforms);
if(status != CL_SUCCESS)
   {
   return 0;
   }
if (0 < numPlatforms)
   {
   cl_platform_id* platforms = new cl_platform_id;
   status = clGetPlatformIDs(numPlatforms, platforms, NULL);

   char platformName;
   for (unsigned i = 0; i < numPlatforms; ++i)
         {
         status = clGetPlatformInfo(platforms,
             CL_PLATFORM_VENDOR,
             sizeof(platformName),
             platformName,
             NULL);

         platform = platforms;
         platformVendor.assign(platformName);

         if (!strcmp(platformName, "Advanced Micro Devices, Inc."))
             {
             break;
             }
         }

   std::cout << "Platform found : " << platformName << "\n";
   delete[] platforms;
   }
页: [1]
查看完整版本: OpenCL 学习step by step (2) 一个简单的OpenCL的程序