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

标签 c linux cpu-usage

我正在尝试在代码中获取程序的 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/

相关文章:

memory - JMeter 加载服务器是否影响我的结果?

mysql - 有没有办法减慢 mysql 查询以降低 CPU 使用率?

java - 使 Java 消耗大量 CPU 的外部进程

c++ - MPI Isend 和 Irecv 问题

linux - 适用于 Linux 的 GPS 导航软件/SDK

linux screen 分离和注销

linux - 为什么Linux中Gradle的wrapper必须要这样启动?

c - 为什么这个程序会出现段错误?

c - 由于重新分配而导致执行错误

c++ - 源.cpp :LINE:COL: error: function definition is not allowed here