Linux 计算进程CPU占用率

下面的代码是为了计算从get_cpu_proc(&cpc[0])到get_cpu_proc(&cpc[1])之间运算的平均CPU占用率的近似值。
for循环没有实际作用,只是让CPU跑起来。
usleep(80000)的调用是为了不让CPU占用率达到100%。
我的CPU频率是2.93G,所以才有:#define CPU_FREQUENCY    2930000000UL。

编译:
g++ -g -W -Wall -Wextra -o mytest main.cpp
执行:
./mytest
停止
Ctrl-C

 

 

main.cpp:

// 2010年 08月 04日 星期三 17:09:13 CST
// author: 李小丹(Li Shao Dan) 字 殊恒(shuheng)
// K.I.S.S
// S.P.O.T

#include <iostream>
#include <cstdlib>
#include <cstdio>

#include <unistd.h>
#include <sys/times.h>

using namespace std;


#define CPU_FREQUENCY    2930000000UL

struct cpu_proc_click {
    unsigned long long cpu;
    unsigned long long proc;
};

static inline unsigned long long currentcycles();
static void inline get_cpu_proc(struct cpu_proc_click *);
static double inline get_cpu_rate(struct cpu_proc_click *);

int main()
{
    struct cpu_proc_click cpc[2];
    unsigned int count = 0;
    double rate = 0;
    for(;;) {
        get_cpu_proc(&cpc[0]);

        for(int i = 0; i < 999; ++i) {
            for(int j = 0; j < 99999; ++j)
                ++count;
        }
        usleep(80000);

        get_cpu_proc(&cpc[1]);

        rate = get_cpu_rate(cpc);
        cout << rate * 100 << endl;
    }
    return 0;
}

static inline unsigned long long currentcycles()
{
    unsigned long long ret;
    __asm__ __volatile__ ("rdtsc" : "=A" (ret));
    return ret;
}

static void inline get_cpu_proc(struct cpu_proc_click *cpc)
{
    struct tms tt;
    times(&tt);
    cpc->proc = tt.tms_utime + tt.tms_stime;
    cpc->cpu = currentcycles();
}

static double inline get_cpu_rate(struct cpu_proc_click *cpc)
{
    return ((double)(cpc[1].proc - cpc[0].proc)
        / ((cpc[1].cpu - cpc[0].cpu) * sysconf(_SC_CLK_TCK))) * CPU_FREQUENCY;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值