简体   繁体   English

如何以百分比百分比获取 C 程序中的 CPU 使用率

[英]How to get CPU usage in C program with percentage %

I try to get a cpu usage with c program but the result does not come out in percentage %, what is wrong with this code?我尝试使用 c 程序获取 CPU 使用率,但结果没有以百分比显示,这段代码有什么问题? Maybe someone can clarify or offer me another way to recover the CPU used.也许有人可以澄清或提供另一种方法来恢复使用的 CPU。

My code:我的代码:

 int GetCPULoad() {
    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);
}

maybe can i do that with /proc/stat file, any one know how to do that?也许我可以用 /proc/stat 文件做到这一点,有人知道该怎么做吗?

i have try another code我尝试了另一个代码


    fp = fopen ("/proc/stat", "r");
    if (fp) {
    long long unsigned int user,nice,system,idle;
    int i = fscanf(fp,"%*s %llu %llu %llu %llu",&user,&nice,&system,&idle);
    int total_cpu_usage1;
    total_cpu_usage1 = user + nice + system + idle;
    sprintf( http_buf,"<br>CPU usage: %d ", total_cpu_usage1); tcp_write(&tcpbuf, sock, http_buf, strlen(http_buf) );
    fclose(fp);
    }

but same result: CPU usage: 159838295但结果相同:CPU 使用率:159838295

how can i get the persentage %?我怎样才能得到百分比?

The simplest way would be with multiple loops that have different ranges and different increments.最简单的方法是使用具有不同范围和不同增量的多个循环。

for (i = 1; i < 10; i++) {
    ...
}
for (i = 10; i <= 30; i += 10) {
    ...
}
for (i = 60; i <= 120; i += 30) {
    ...
}

If you really have to do it in a single loop:如果您真的必须在一个循环中执行此操作:

for (i = 1; i <= 120; 
        i = i < 10 ? i + 1 : 
                     (i < 30 ? i + 10 : i + 30))

The last part of the for loop header increments i by different values depending on the range it's in. for循环的最后一部分 header 将i增加不同的值,具体取决于它所在的范围。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM