我正在尝试学习cuda编程,当我尝试从本教程here执行向量加法程序时,它没有按预期运行,没有引发任何错误,但是答案不正确。
#include<stdio.h>
#include<stdlib.h>
#define N 20
__global__ void add(int *a, int *b, int *c){
c[blockIdx.x] = a[blockIdx.x] + b[blockIdx.x];
}
int main(void) {
int *a, *b, *c; // host copies of a, b, c
int *d_a, *d_b, *d_c; // device copies of a, b, c
int size = N * sizeof(int), i;
// Alloc space for device copies of a, b, c
cudaMalloc((void **)&d_a, size);
cudaMalloc((void **)&d_b, size);
cudaMalloc((void **)&d_c, size);
// Alloc space for host copies of a, b, c and setup input values
a = (int *)malloc(size);
b = (int *)malloc(size);
c = (int *)malloc(size);
for(i = 0; i< N ; i++){
a[i] = rand() % 100;
b[i] = rand() % 50;
}
// Copy inputs to device
cudaMemcpy(d_a, a, size, cudaMemcpyHostToDevice);
cudaMemcpy(d_b, b, size, cudaMemcpyHostToDevice);
// Launch add() kernel on GPU with N blocks
add<<<N,1>>>(d_a, d_b, d_c);
cudaDeviceSynchronize();
// Copy result back to host
cudaMemcpy(c, d_c, size, cudaMemcpyDeviceToHost);
// Cleanup
for(i = 0; i< N; i++)
printf("%d + %d = %d\n", a[i], b[i], c[i]);
free(a); free(b); free(c);
cudaFree(d_a); cudaFree(d_b); cudaFree(d_c);
return 0;
}
结果总是显示为-1,我不知道为什么,有人可以在这里帮助我吗?
答案 0 :(得分:0)
我只是使用我的GPU来编译和运行程序,并且它按预期运行。您必须检查cudaMalloc
和cudaMemCpy
返回的错误代码,并确保它们没有返回任何错误。