C语言中的cpu利用率

C语言中的cpu利用率,c,linux,C,Linux,我尝试使用C获得%的CPU利用率。我看到了以下解决方案: 因此,我尝试了那里提供的帮助: #include <time.h> #include <stdio.h> #include <stdlib.h> #include <sys/times.h> #include <unistd.h> #define NANO2SEC 1000000000 struct timespec gettimenow; double getWtime; d

我尝试使用C获得%的CPU利用率。我看到了以下解决方案:

因此,我尝试了那里提供的帮助:

#include <time.h>
#include <stdio.h>
#include <stdlib.h>
#include <sys/times.h>
#include <unistd.h>
#define NANO2SEC 1000000000

struct timespec gettimenow;
double getWtime;
double getCtick;
int ncore;
double cpu_util;

double get_wall_time () {
    if (clock_gettime(CLOCK_REALTIME,&gettimenow)){
        //error handle
        return 0;
    }
    return ( (double)gettimenow.tv_sec + ( (double)gettimenow.tv_nsec / NANO2SEC ) );
}


double get_cpu_time () {
    return ( (double)clock() / sysconf (_SC_CLK_TCK));
}

int core_logical () {
    return (sysconf(_SC_NPROCESSORS_ONLN));
}

void main() {
    getWtime = get_wall_time ();
    printf("\nWall time : %f \n", getWtime);

    getCtick = get_cpu_time ();
    printf("\nCPU time : %f \n", getCtick);

    ncore = core_logical ();
    printf("\nNo of cores : %d \n", ncore);

    cpu_util = (getCtick/ncore/getWtime);
    printf("\nCPU Utilization : %f %% \n", cpu_util);
}
#包括
#包括
#包括
#包括
#包括
#定义NANO2SEC 100000000
结构timespec gettimenow;
双getWtime;
双格特克;
int ncore;
双cpu_-util;
双进站时间(){
if(clock\u gettime(clock\u REALTIME和gettimenow)){
//错误句柄
返回0;
}
返回((双精度)gettimenow.tv_sec+((双精度)gettimenow.tv_nsec/NANO2SEC));
}
双倍获取cpu时间(){
返回((双)时钟()/sysconf(_SC_CLK_TCK));
}
int核心逻辑(){
返回(sysconf(_SC_NPROCESSORS_ONLN));
}
void main(){
getWtime=get_wall_time();
printf(“\n所有时间:%f\n”,getWtime);
getCtick=get_cpu_time();
printf(“\nCPU时间:%f\n”,getCtick);
ncore=core_logical();
printf(“\n没有核心:%d\n”,n核心);
cpu_util=(getCtick/ncore/getWtime);
printf(“\nCPU利用率:%f%%\n”,cpu\u util);
}
o/p:

墙时间:1439132892.054816

CPU时间:17280000

芯数:2

CPU利用率:0.000000%

但使用top命令时,我发现cpu利用率根本不是0%,而是更多。即6.2%
我想知道当前CPU利用率的百分比。

您的程序所做的没有任何意义

将返回当前进程使用的CPU时间量的
clock()
除以自1970年以来的秒数。当然,这并没有给你一个有意义的答案

如果要获取系统的当前CPU使用情况,需要使用
/proc/uptime
提供的数据。读取时,此文件返回两个数字,表示系统运行的秒数和空闲的秒数。因此,要查找当前的CPU使用情况:

  • 打开并读取文件,保存您得到的两个数字。让我们称它们为
    uptime1
    idle1
    。关上它

  • 等一下

  • 再次打开并读取文件;将数字另存为
    uptime2
    idle2

  • 这一秒的CPU使用率为
    100-100*(idle2-idle1)/(uptime2-uptime1)


  • @Anton.P相同的结果您希望获得哪些cpu使用率?系统?进程?@表示系统的cpu总利用率,单位为%,进程正常运行时间是系统提供的已计算值。我想通过c计算。不想做系统call@Zim
    top
    根据
    /proc
    中的信息计算其所有数字。使用
    /proc
    并没有什么丢脸的地方。它和任何系统调用一样都是内核接口的一部分,而且它是唯一有大量信息可用的地方。@OtherGuy和proc必须从其他来源获取信息,因此我希望直接测量,而不是通过shell@Zim不,没有。从
    /proc
    中的伪文件读取直接从内核获取信息。