gpt4 book ai didi

c - 程序中如何获取某个进程的CPU使用率?

转载 作者:行者123 更新时间:2023-11-30 20:40:00 25 4
gpt4 key购买 nike

我正在尝试在代码中获取程序的 CPU 使用情况。我使用了下面的代码,但它返回了总 CPU 使用率。有没有办法只获取我的程序的使用情况?

int FileHandler;
char FileBuffer[1024];
float load;

FileHandler = open("/proc/loadavg", O_RDONLY);
if(FileHandler < 0) {
return -1; }
read(FileHandler, FileBuffer, sizeof(FileBuffer) - 1);
sscanf(FileBuffer, "%f", &load);
close(FileHandler);
return (int)(load * 100);

最佳答案

您可以使用 popen()ps 作为命令:

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

FILE *popen(const char *command, const char *mode);
int pclose(FILE *stream);

int main(void)
{
FILE *cmd;
char s[64];
double cpu;

sprintf(s, "ps --no-headers -p %d -o %%cpu", (int)getpid());
cmd = popen(s, "r");
if (cmd == NULL) {
perror("popen");
exit(EXIT_FAILURE);
}
if (fgets(s, sizeof(s), cmd) != NULL) {
cpu = strtod(s, NULL);
printf("%f\n", cpu);
}
pclose(cmd);
return 0;
}

关于c - 程序中如何获取某个进程的CPU使用率?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24801733/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com