选择当前显存占用率较低的英伟达显卡

众寻多种方法,还是没有找到C++中能获得显卡使用状况的简单方法,所以这里绕了个弯,把目标转换成了字符串处理.

获取当前设备显卡的基本信息

虽然没找到获得显卡运行时的状况的函数,但获取显卡的基本信息是比较常见的.方法如下:

#include <cuda_runtime.h>
#include <cuda_runtime_api.h>
#include <cudnn.h>
#include <cublas_v2.h>
#include <device_launch_parameters.h>

int  count = 0;
cudaDeviceProp prop;
cudaGetDeviceCount(&count);
printf("count:%d\n",count);

借用cuda库调用查看当前显卡数量.此外也有其他基本信息,如显存大小等等,可以直接查看,不再赘述.

获取显卡当前运行状况

调用英伟达的程序查询.装好显卡驱动后,Linux可以直接在命令行

nvidia-smi

C++程序通过调用命令行结果获取:

FILE *fstream=NULL;
char buff[10240];
memset(buff,0,sizeof(buff));
// 命令行执行,结果放在fstream内
if(NULL==(fstream=popen("nvidia-smi","r")))
{
    fprintf(stderr,"execute command failed: %s",strerror(errno));
    //return;
}
char *buff_dst;
buff_dst = new char [20480];
//从fstream流内读取结果
while(NULL!=fgets(buff, sizeof(buff), fstream)) {
        strcat(buff_dst,buff);
        //printf("%s",buff);
}
pclose(fstream);

获取使用率较低的显卡

接下来转为处理字符串,从结果中获取使用显存较低的显卡.经过观察发现”MiB”前面是显存.其中单数”MiB”表示当前已使用大小,双数表示显卡总显存.

int searchStr(char *src,char *str)
{
    printf("%s,%s\n",src,str);
    char *p = src;
    char *q = str;
    int index = 0;
    int count = 0;

    while(*p != '\0')
    {
        if(*q == '\0')
        {
            return index;
        }
        if(*p == *q)
        {
            p++;
            q++;
            index++;
            continue;
        }
        p++;
        q = str;
        index++;

    }
    return 0;
}

比较

咳咳,刚刚拿到了每块显卡的已使用显存大小,只要比较下选最小的就行了.
结束.

代码地址:https://download.csdn.net/download/san_junipero/10437721

猜你喜欢

转载自blog.csdn.net/san_junipero/article/details/80452735
今日推荐