我使用CUDA-5.5在Ubuntu 12.04CUDA編譯,矢量添加不正確
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <unistd.h>
#include <cuda_runtime_api.h>
#include <cuda.h>
#include "book.h"
__global__ void add(int *a, int *b, int *c){
int tid = blockIdx.x;
if (tid < 10)
c[tid] = a[tid] + b[tid];
}
int main(void) {
int a[10],b[10],c[10];
int *dev_a,*dev_b,*dev_c;
cudaError_t err = cudaMalloc((void**)&dev_a, 10 * sizeof(int)) ;
if(err != cudaSuccess){
printf("The error is %s", cudaGetErrorString(err));
}
cudaError_t err2 = cudaMalloc((void**)&dev_b, 10 * sizeof(int)) ;
if(err2 != cudaSuccess){
printf("The error is %s", cudaGetErrorString(err));
}
cudaError_t err3 = cudaMalloc((void**)&dev_c, 10 * sizeof(int)) ;
if(err3 != cudaSuccess){
printf("The error is %s", cudaGetErrorString(err));
}
for (int i = 0; i<10 ; i++)
{
a[i] = -i;
b[i] = i*i;
}
cudaError_t err4 = cudaMemcpy(dev_a,a,10*sizeof(int), cudaMemcpyHostToDevice) ;
if(err4 != cudaSuccess){
printf("The error is %s", cudaGetErrorString(err));
}
cudaError_t err5 =cudaMemcpy(dev_b,b,10*sizeof(int), cudaMemcpyHostToDevice) ;
if(err5 != cudaSuccess){
printf("The error is %s", cudaGetErrorString(err));
}
add<<<10,1>>>(dev_a,dev_c,dev_c);
if (cudaPeekAtLastError() != cudaSuccess) {
printf("The error is %s", cudaGetErrorString(cudaGetLastError()));
}
cudaError_t err6 = cudaMemcpy(c,dev_c,10*sizeof(int), cudaMemcpyDeviceToHost);
if(err6 != cudaSuccess){
printf("The error is %s", cudaGetErrorString(err));
}
for (int i = 0; i<10; i++)
{
printf("%d + %d = %d\n", a[i],b[i],c[i]);
}
cudaFree(dev_a);
cudaFree(dev_b);
cudaFree(dev_c);
return 0 ;
}
此代碼編譯沒有錯誤,但給人的廢話答案上運行我的GTX570一個簡單的代碼:
0 + 0 = -1087278592
-1 + 1 = -1245725046
-2 + 4 = 2139095032
-3 + 9 = 780509949
-4 + 16 = 1195091696
-5 + 25 = -921707890
-6 + 36 = 33554408
-7 + 49 = 936179122
-8 + 64 = 1026206341
-9 + 81 = -1090519076
是,我從cuda網站獲得了cuda代碼 https://developer.nvidia.com/cuda-downloads 是的,我從nvidia網站獲得了nvidia驅動程序 http://www.geforce.com/drivers/results/67567
我得到這個以前運行,但後來我超級duper-破壞我的Ubuntu分區,現在我遇到了麻煩。
編輯: 解決它,至少它似乎工作。我用valgrind發現函數fwrite是segfaulting。奇怪的是,在我的電腦上寫入段錯誤,而不是在之前運行我的模擬的服務器上。
敢問一個關於fwrite段落錯誤與您發佈的代碼或CUDA中的任何內容有什麼關係? – talonmies