CUDA 二维矩阵操作

二维矩阵

代码如下:

#include <stdio.h>

#include <stdlib.h>
#include"cuda_runtime.h"
#include"device_launch_parameters.h"
#include"iostream"
using namespace std;
/************************************************************************/
/* Example:矩阵加法                                                              */
const int N =10;
__global__ void add(float m[][N], float n[][N]);
void main()
{
float(*a)[N] = new float[N][N];
float(*b)[N] = new float[N][N];
float(*dev_a)[N], (*dev_b)[N];
cout << "a:" << endl;
for (int i = 0; i < N; i++)
{
for (int  j = 0; j < N; j++)
{
a[i][j] = i + j;
cout << a[i][j] << "  ";
}
cout << endl;
}
cudaMalloc((void **)&dev_a, N * N * sizeof(float));
cudaMalloc((void **)&dev_b, N * N * sizeof(float));
cudaMemcpy(dev_a, a, N * N * sizeof(float), cudaMemcpyHostToDevice);
// delete[]a;
dim3 blocks(N, N);
dim3 threads(1);
add << <blocks, threads >> >(dev_a, dev_b);
cudaMemcpy(b, dev_b, N * N * sizeof(float), cudaMemcpyDeviceToHost);
cudaFree(dev_a);
cudaFree(dev_b);
cout << "b:" << endl;
for (int i = 0; i < N; i++)
{
for (int j = 0; j < N; j++)
{
cout << b[i][j] << "  ";
}
cout << endl;
}
delete[]b;
}
__global__ void add(float m[][N], float n[][N])
{
int x = threadIdx.x + blockIdx.x * blockDim.x;
int y = threadIdx.y + blockIdx.y * blockDim.y;
{
n[x][y] = 200*m[x][y];
}
}

你可能感兴趣的:(C++,CUDA)