VScode configures cuda development environment

Because of the course learning needs, configure Nvidia's cuda environment to do high-performance computing tests.

1.cuda installation

First of all, go to the official website of Nvidia to download and install cuda. ​​The installation path can be freely selected, but for the convenience of operation, it is recommended to install all by default.

You can execute nvidia-smi.exe from the command line to view the highest cuda version supported by the current graphics card. The cuda version in the upper right corner is the version we want to confirm. The downloaded cuda should not be newer than this version.

cuda download entry: CUDA Toolkit 12.1 Update 1 Downloads | NVIDIA Developer 

After entering, select the corresponding platform and version

2. Check the environment configuration

Under normal circumstances, the environment variables will be automatically configured after the installation is complete, but to be on the safe side, let's go to the command line to have a look

 Execute nvcc -V, if the version number and other information can be displayed normally, it means the installation is normal.

3. Configure vscode

cuda programming uses .cu files. I use the coderunner plug-in for easy operation to configure the compilation of .cu files.

Click on the little gear to select Extended Settings

 

We edit directly in settings.json

 Add the compilation statement of the cu file in "code-runner.executorMap": {}

"cu": "cd $dir; nvcc $fileName -o $fileNameWithoutExt.exe -I'C:\\Program Files\\NVIDIA GPU Computing Toolkit\\CUDA\\v11.7\\include\\CL' && $dir$fileNameWithoutExt",
//请设置和你的安装路径一致的地址

Then we click the run symbol in the upper right corner of the .cu file and choose to run with coderunner

Below is a small test program

#include <iostream>
#include <math.h>
__global__ 
void add(int n, float *x, float *y)
{
    for (int i = 0; i < n; i++)
    y[i] = x[i] + y[i];
}

int main(void)
{
    int N = 1<<25;
    float *x, *y;

    cudaMallocManaged(&x, N*sizeof(float));
    cudaMallocManaged(&y, N*sizeof(float));

    for (int i = 0; i < N; i++) {
    x[i] = 1.0f;
    y[i] = 2.0f;
}

    add<<<1, 1>>>(N, x, y);

    cudaDeviceSynchronize();

    float maxError = 0.0f;
    for (int i = 0; i < N; i++)
    maxError = fmax(maxError, fabs(y[i]-3.0f));
    std::cout << "Max error: " << maxError << std::endl;

    cudaFree(x);
    cudaFree(y);

    return 0;
}

The normal operation results are as follows

 

An error may be returned here, to the effect that cl.exe cannot be found in the path

If this is the case we can add a path system environment variable

C:\Program Files\Microsoft Visual Studio\2022\Community\VC\Tools\MSVC\14.33.31629\bin\Hostx64\x64
//注意这里要找到你电脑上的visual studio安装路径,找到这个文件,bin目录下面可能有两个文件夹,但是cuda运行一定要选择x64

Then restart your vscode, and then use coderunner to run normally

Guess you like

Origin blog.csdn.net/lijj0304/article/details/130810197