cuda 编 程cuda 实现向量加法
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了cuda 编 程cuda 实现向量加法相关的知识,希望对你有一定的参考价值。
#include <math.h>
#include <stdio.h>
#include <iostream>
using namespace std;
const double EPSILON = 1.0e-15;
const double a = 1.23;
const double b = 2.34;
const double c = 3.57;
void __global__ add(const double *x, const double *y, double *z, const int N);
void check(const double *z, const int N);
int main(void)
const int N = 1001;
const int M = sizeof(double) * N;
double *h_x = (double*) malloc(M);
double *h_y = (double*) malloc(M);
double *h_z = (double*) malloc(M);
for (int n = 0; n < N; ++n)
h_x[n] = a;
h_y[n] = b;
double *d_x, *d_y, *d_z;
cudaMalloc((void **)&d_x, M);
cudaMalloc((void **)&d_y, M);
cudaMalloc((void **)&d_z, M);
cudaMemcpy(d_x, h_x, M, cudaMemcpyHostToDevice);
cudaMemcpy(d_y, h_y, M, cudaMemcpyHostToDevice);
const int block_size = 128;
const int grid_size = (N + block_size - 1) / block_size;
add<<<grid_size, block_size>>>(d_x, d_y, d_z, N);
cudaMemcpy(h_z, d_z, M, cudaMemcpyDeviceToHost);
check(h_z, N);
for (int n = 0; n < N; ++n)
cout<<h_z[n]<<endl;
free(h_x);
free(h_y);
free(h_z);
cudaFree(d_x);
cudaFree(d_y);
cudaFree(d_z);
return 0;
void __global__ add(const double *x, const double *y, double *z, const int N)
const int n = blockDim.x * blockIdx.x + threadIdx.x;
if (n < N)
z[n] = x[n] + y[n];
void check(const double *z, const int N)
bool has_error = false;
for (int n = 0; n < N; ++n)
if (fabs(z[n] - c) > EPSILON)
has_error = true;
printf("%s\\n", has_error ? "Has errors" : "No errors");
nvcc add3if.cu -o add3o
./add3o
以上是关于cuda 编 程cuda 实现向量加法的主要内容,如果未能解决你的问题,请参考以下文章
cuda 编 程 helloworld 打印grid 与block