C++ 从c运行nvidia smi
我试着使用popen从c获得nvidia smi命令的输出,如下所示 命令存储在缓冲区字符串中,并使用相同的字符串存储输出:C++ 从c运行nvidia smi,c++,shell,command-line,gpu,C++,Shell,Command Line,Gpu,我试着使用popen从c获得nvidia smi命令的输出,如下所示 命令存储在缓冲区字符串中,并使用相同的字符串存储输出: const size_t pid = getpid(); char pid_s[1000]; sprintf(pid_s, "%lu", pid); FILE *file_command = NULL; char buffer[1000]; sprintf(buffer, "nvidia-smi | grep %
const size_t pid = getpid();
char pid_s[1000];
sprintf(pid_s, "%lu", pid);
FILE *file_command = NULL;
char buffer[1000];
sprintf(buffer, "nvidia-smi | grep %s |awk '{print $6}'", pid_s);
file_command = popen(buffer, "r");
if (file_command == NULL) //No error : file_command is not NULL
{
throw std::runtime_error("Command failed to execute");
}
sleep(4); //To get time for the command to be executed.
while (fgets(buffer, sizeof(buffer), file_command) != NULL) //Read output
{
printf("Result from command %s \n", buffer); //Nothing printed
}
我尝试获取nvidia smi output的第6个参数,它是当前正在运行的程序的内存(其pid取自getpid()
屏幕上没有打印任何内容
虽然GPU上已分配内存(使用cudaMalloc),但fgets返回NULL
我一直在按照这篇文章的建议使用睡眠
我终于找到了一种更好的方法,通过使用 如中所建议的
c语言的使用非常简单(请参见示例)您确实意识到,当NVidia更改
NVidia smi
的输出格式时,这种方法是脆弱的,可能会随时中断-对吗?是的。这可能不是最好的办法。我需要一种直接从c获取GPU上进程的内存消耗的方法。cudaMemGetInfo函数提供我不感兴趣的总内存和空闲内存