关闭

Linux 计算进程CPU占用率

发表于:2010-8-12 10:26

字体: | 上一篇 | 下一篇 | 我要投稿

 作者:leeshuheng    来源:51Testing软件测试网采编

  下面的代码是为了计算从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;
}

《2023软件测试行业现状调查报告》独家发布~

关注51Testing

联系我们

快捷面板 站点地图 联系我们 广告服务 关于我们 站长统计 发展历程

法律顾问:上海兰迪律师事务所 项棋律师
版权所有 上海博为峰软件技术股份有限公司 Copyright©51testing.com 2003-2024
投诉及意见反馈:webmaster@51testing.com; 业务联系:service@51testing.com 021-64471599-8017

沪ICP备05003035号

沪公网安备 31010102002173号