【发布时间】:2020-08-29 08:33:20
【问题描述】:
尝试使用 nvcc 从命令提示符运行 CUDA 程序,但 GPU 代码似乎没有按预期运行。完全相同的代码在 Visual Studio 上成功运行并输出预期的输出。
nvcc -arch=sm_60 -std=c++11 -o test.cu test.exe
test.exe
环境: 视窗 10, 英伟达 Quadro k4200, CUDA 10.2
源代码
#include <stdio.h>
#include <stdlib.h>
#include <vector>
#include <iostream>
/* this is the vector addition kernel.
:inputs: n -> Size of vector, integer
a -> constant multiple, float
x -> input 'vector', constant pointer to float
y -> input and output 'vector', pointer to float */
__global__ void saxpy(int n, float a, const float x[], float y[])
{
int id = threadIdx.x + blockDim.x*blockIdx.x; /* Performing that for loop */
// check to see if id is greater than size of array
if(id < n){
y[id] += a*x[id];
}
}
int main()
{
int N = 256;
//create pointers and device
float *d_x, *d_y;
const float a = 2.0f;
//allocate and initializing memory on host
std::vector<float> x(N, 1.f);
std::vector<float> y(N, 1.f);
//allocate our memory on GPU
cudaMalloc(&d_x, N*sizeof(float));
cudaMalloc(&d_y, N*sizeof(float));
//Memory Transfer!
cudaMemcpy(d_x, x.data(), N*sizeof(float), cudaMemcpyHostToDevice);
cudaMemcpy(d_y, y.data(), N*sizeof(float), cudaMemcpyHostToDevice);
//Launch the Kernel! In this configuration there is 1 block with 256 threads
//Use gridDim = int((N-1)/256) in general
saxpy<<<1, 256>>>(N, a, d_x, d_y);
//Transfering Memory back!
cudaMemcpy(y.data(), d_y, N*sizeof(float), cudaMemcpyDeviceToHost);
std::cout << y[0] << std::endl;
cudaFree(d_x);
cudaFree(d_y);
return 0;
}
输出
1
预期输出
3
我尝试过的事情
当我第一次尝试使用 nvcc 进行编译时,出现了与此处讨论的相同的错误。
Cuda compilation error: class template has already been defined
所以我尝试了建议的解决方案 “现在:D:\Program Files (x86)\Microsoft Visual Studio\2019\Community\VC\Tools\MSVC\14.22.27905\bin\Hostx64\x64” 现在它编译并运行,但输出不符合预期。
【问题讨论】:
-
不是说它解决了你的问题,而是
-o test.cu test.exe或-o test.exe test.cu? -
另外,
-arch=sm_60是 Quadro K4200 的不正确拱形规格。应该是-arch=sm_30。当遇到 CUDA 代码问题时,最好使用proper CUDA error checking。如果您使用-arch=sm_60编译此代码并在 Quadro K4200 上运行它,您会得到一些信息丰富的错误输出。我的建议是在向其他人寻求帮助之前使用适当的 CUDA 错误检查。 -
太棒了。
-arch=sm_30是解决方案。下次我会做错误检查。感谢您提供的重要信息。
标签: c++ visual-studio cuda gpu nvcc