关于矩阵变化的3种做法(1)

指导老师交给我们一个任务

让有1的部分加1,
2的部分加2,
3的部分加3,
4的部分加4.

一开是我对OpenCL的映射不是很清楚,于是不知道该如何分配线程来解决这个问题,
后来我想到了一个”简便“算法,这不就是相当于每个部分乘以2吗?于是我一开始
内核代码是这样写的:
//矩阵变化
const char *KernelSource=
"__kernel void add(__global int *outputB,__global int *inputA)"
"{"
"    int i=get_global_id(0);"
"    outputB[i]=inputA[i]*2;"
"};";

整个部分源代码如下:


#include<stdio.h>
#include<stdlib.h>
#include<CL/cl.hpp>

//矩阵变换
const char *KernelSource=
"__kernel void add(__global int *outputB,__global int *inputA)"
"{"
"    int i=get_global_id(0);"
"    outputB[i]=inputA[i]*2;"
"};";

int main()
{
const int Row=8;
const int Line=8;
int i,j,k;
const size_t datasize=sizeof(int)*Row*Line;
int A[Row][Line]=
{
1,1,1,1,2,2,2,2,
1,1,1,1,2,2,2,2,
1,1,1,1,2,2,2,2,
1,1,1,1,2,2,2,2,
3,3,3,3,4,4,4,4,
3,3,3,3,4,4,4,4,
3,3,3,3,4,4,4,4,
3,3,3,3,4,4,4,4
};
int B[Row][Line];
cl_int err;
cl_platform_id platform;
err=clGetPlatformIDs(1,&platform,NULL);
cl_device_id device;
err=clGetDeviceIDs(platform,CL_DEVICE_TYPE_GPU,1,&device,NULL);
cl_context context;
context=clCreateContext(NULL,1,&device,NULL,NULL,&err);
cl_command_queue cmdQueue;
cmdQueue=clCreateCommandQueue(context,device,NULL,&err);
cl_mem BufferA;
cl_mem BufferB;
BufferA=clCreateBuffer(context,CL_MEM_READ_ONLY,datasize,NULL,&err);
BufferB=clCreateBuffer(context,CL_MEM_WRITE_ONLY,datasize,NULL,&err);
err=clEnqueueWriteBuffer(cmdQueue,BufferA,CL_TRUE,0,datasize,A,0,NULL,NULL);
cl_program program;
program=clCreateProgramWithSource(context,1,&KernelSource,NULL,&err);
err=clBuildProgram(program,1,&device,NULL,NULL,NULL);
cl_kernel kernel;
kernel=clCreateKernel(program,"add",&err);
err=clSetKernelArg(kernel,0,sizeof(cl_mem),&BufferB);
err=clSetKernelArg(kernel,1,sizeof(cl_mem),&BufferA);
size_t globalWorkSize[1]={64};
err=clEnqueueNDRangeKernel(cmdQueue,kernel,1,NULL,globalWorkSize,NULL,0,NULL,NULL);
err=clEnqueueReadBuffer(cmdQueue,BufferB,CL_TRUE,0,datasize,B,0,NULL,NULL);
for(i=0;i<Row;i++)
{
for(j=0;j<Line;j++)
{
printf("%d ",B[i][j]);
}
printf("\n");
}
system("pause");

得到了这样的结果:


虽然这样能完成任务,但后来一想,
这应该不是老师叫我们做这个是的目的,
于是开始研究了线程的分配,总算有所收获。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值