如何在WSL2中安装可执行编译.cu文件的cuda环境

发布时间 2023-04-10 16:50:37作者: Death_Knight

参考nvidia官方文档:

https://docs.nvidia.com/cuda/wsl-user-guide/index.html#installing-insider-preview-builds

 

 

=========================================

 

 

第一步:

sudo apt-key del 7fa2af80

 

第二步:

sudo apt install nvidia-cuda-toolkit

 

 

注意:

本文方法是唯一成功的方法,如果采用和物理机ubuntu一样的在nvidia官网下载cuda版本,然后手动安装,那么在编译好.cu文件后运行则会报错,报错信息为无法检测到显卡/显卡驱动。

 

测试代码:

x.cu

#include <stdio.h>
#include <stdlib.h>
#include <cuda_runtime.h>

//初始化CUDA
int count=0;

bool InitCUDA()
{
    printf("Start to detecte devices.........\n");//显示检测到的设备数

    cudaGetDeviceCount(&count);//检测计算能力大于等于1.0 的设备数

    if(count == 0)
    {
        fprintf(stderr, "There is no device.\n");
        return false;
    }

    printf("%d device/s detected.\n",count);//显示检测到的设备数

    int i;
    for(i = 0; i < count; i++)
    {//依次验证检测到的设备是否支持CUDA
        cudaDeviceProp prop;
        if(cudaGetDeviceProperties(&prop, i) == cudaSuccess) 
        {//获得设备属性并验证是否正确
            if(prop.major >= 1)//验证主计算能力,即计算能力的第一位数是否大于1
            {
                printf("Device %d: %s supportsCUDA %d.%d.\n",i+1,prop.name,prop.major,prop.minor);//显示检测到的设备支持的CUDA 版本
                break;
            }
        }
    }

    if(i == count) 
    {//没有支持CUDA1.x 的设备
        fprintf(stderr, "There is no device supporting CUDA 1.x.\n");
        return false;
    }

    cudaSetDevice(i);//设置设备为主叫线程的当前设备
    return true;
}

int main()
{
    if(!InitCUDA()) 
    {//初始化失败返回系统int argc, char** argv
        return 0;
    }

    printf("Hello GPU! CUDA has been initialized.\n");

    //exit(argc ? EXIT_SUCCESS : EXIT_FAILURE);
    return 0;//返回系统
}

 

 

y.cu

#include <iostream>
#include <math.h>
#include <cuda_runtime.h>
using namespace std;
int main() {
    int count = 0;
        cudaGetDeviceCount(&count);
        cout <<"当前计算机包含GPU数为"<< count << endl;
    cudaError_t err = cudaGetDeviceCount(&count);
    if (err != cudaSuccess) 
            printf("%s\n", cudaGetErrorString(err));


    cudaDeviceProp prop;
    cudaGetDeviceProperties(&prop, 0);
    printf("Device Number: %d\n", 0);
    cout << "当前设备名字为" << prop.name << endl;
        cout << "GPU全局内存总量为" << prop.totalGlobalMem << endl;
        cout << "单个线程块中包含的线程数最多为" << prop.maxThreadsPerBlock << endl;
  
}

 

 

效果:

 

 

 

 

 

=========================================