Linux下没有直接可以调用系统函数知道CPU占用和内存占用。那么如何知道CPU和内存信息呢。只有通过proc伪文件系统来实现。

proc伪文件就不介绍了,只说其中4个文件。一个是/proc/stat,/proc/meminfo,/proc/<pid>/status,/proc/<pid>/stat

proc/stat:存放系统的CPU时间信息

该文件包含了所有CPU活动的信息,该文件中的所有值都是从系统启动开始累计到当前时刻。不同内核版本中该文件的格式可能不大一致,以下通过实例来说明数据该文件中各字段的含义。

实例数据:2.6.24-24版本上的

fjzag@fjzag-desktop:~$ cat /proc/stat

cpu 38082 627 27594 893908 12256 581 895 0 0

cpu0 22880 472 16855 430287 10617 576 661 0 0

cpu1 15202 154 10739 463620 1639 4 234 0 0

intr 120053 222 2686 0 1 1 0 5 0 3 0 0 0 47302 0 0 34194 29775 0 5019 845 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0

ctxt 1434984

btime 1252028243

processes 8113

procs_running 1

procs_blocked 0

第一行的数值表示的是CPU总的使用情况,所以我们只要用第一行的数字计算就可以了。下表解析第一行各数值的含义:

参数 解析(单位:jiffies)

(jiffies是内核中的一个全局变量,用来记录自系统启动一来产生的节拍数,在linux中,一个节拍大致可理解为操作系统进程调度的最小时间片,不同linux内核可能值有不同,通常在1ms到10ms之间)

user (38082) 从系统启动开始累计到当前时刻,处于用户态的运行时间,不包含 nice值为负进程。

nice (627) 从系统启动开始累计到当前时刻,nice值为负的进程所占用的CPU时间

system (27594) 从系统启动开始累计到当前时刻,处于核心态的运行时间

idle (893908) 从系统启动开始累计到当前时刻,除IO等待时间以外的其它等待时间iowait (12256) 从系统启动开始累计到当前时刻,IO等待时间(since 2.5.41)

irq (581) 从系统启动开始累计到当前时刻,硬中断时间(since 2.6.0-test4)

softirq (895) 从系统启动开始累计到当前时刻,软中断时间(since 2.6.0-test4)stealstolen(0) which is the time spent in other operating systems when running in a virtualized environment(since 2.6.11)

guest(0) which is the time spent running a virtual CPU for guest operating systems under the control of the Linux kernel(since 2.6.24)

结论2:总的cpu时间totalCpuTime = user + nice + system + idle + iowait + irq + softirq + stealstolen + guest

可以利用scanf,sscanf,fscanf读取这些信息,具体可以查man proc.我的程序中只取了前4个。

/proc/meminfo:存放系统的内存信息

[ubuntu@root ~]#cat /proc/meminfo
MemTotal:        2061616 kB
MemFree:         1093608 kB
Buffers:          151140 kB
Cached:           479372 kB
SwapCached:            0 kB
Active:           516964 kB
Inactive:         374672 kB
Active(anon):     261412 kB
Inactive(anon):     5604 kB
Active(file):     255552 kB
Inactive(file):   369068 kB

……

别的就不说了,主要看第一个MemTotal,系统总的物理内存,它比真实的物理内存要小一点

/proc/<pid>/status:存放进程的CPU时间信息以及一些综合信息

[ubuntu@root ~]#cat /proc/889/status
Name:    Xorg
State:    S (sleeping)
Tgid:    889
Pid:    889
PPid:    881
TracerPid:    0
Uid:    0    0    0    0
Gid:    0    0    0    0
FDSize:    256
Groups:   
VmPeak:       99036 kB
VmSize:       52424 kB
VmLck:           0 kB
VmHWM:       57004 kB
VmRSS:       45508 kB
VmData:       35668 kB
VmStk:         136 kB
VmExe:        1660 kB
VmLib:        6848 kB
VmPTE:         120 kB
VmPeak是占用虚拟内存的峰值,也就是最高的一个值,而且是虚拟内存,所以有时候会比物理内存要大。PS和TOP指令都是利用VmPeak计算内存占用的。

VmRSS是进程所占用的实际物理内存。

/proc/<pid>/stat:保存着进程的CPU信息。

[ubuntu@root ~]#cat /proc/889/stat
889 (Xorg) S 881 889 889 1031 889 4202752 5307477 0 0 0 34943 12605 0 0
20 0 1 0 8146 89399296 11377 4294967295 134512640 136211844 3221201472
3221200460 5456930 0 0 3149824 1367369423 3223423286 0 0 17 0 0 0 0 0 0

pid=889 进程号

utime=34943 该任务在用户态运行的时间,单位为jiffies

stime=12605 该任务在核心态运行的时间,单位为jiffies

cutime=0 所有已死线程在用户态运行的时间,单位为jiffies

cstime=0 所有已死在核心态运行的时间,单位为jiffies

可以利用scanf,sscanf,fscanf读取这些信息,具体可以查man proc.

结论3:进程的总Cpu时间processCpuTime = utime + stime + cutime + cstime,该值包括其所有线程的cpu时间。

下面粘贴一下本人写的调用接口

//get_cpu.h

#ifndef __GET_CPU__
#define __GET_CPU__ #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <algorithm>
#include <vector>
#define PROCESS_ITEM 14 typedef struct
{
pid_t pid;
unsigned int utime; //live thread at user status (jiffies)
unsigned int stime; //live thread at kernel status
unsigned int cutime; //killed thread at user status
unsigned int cstime; //killed thread at kernel status
}process_cpu_occupy; vector<unsigned int>total_cpu_time; unsigned int get_cpu_process_occupy(const pid_t p);
const char* get_items(const char* buffer,int ie); extern float get_cpu(pid_t p);
extern unsigned int get_total_cpu(); #endif
//get_cpu.cc

#include "get_cpu.h"
const char* get_items(const char* buffer,int ie)
{
assert(buffer);
char* p = buffer;
int len = strlen(buffer);
int count = ;
int i; if ( == ie || ie < )
{
return p;
} for (i=; i<len; i++)
{
if (' ' == *p)
{
count++;
if (count == ie-)
{
p++;
break;
}
}
p++;
} return p;
}
unsigned int get_cpu_process_occupy(const pid_t p)
{
char file[] = {};
process_cpu_occupy t;
FILE *fd;
char line_buff[] = {}; sprintf(file,"/proc/%d/stat",p); fd = fopen (file, "r");
fgets (line_buff, sizeof(line_buff), fd);
sscanf(line_buff,"%u",&t.pid);
char* q = get_items(line_buff,PROCESS_ITEM);
sscanf(q,"%u %u %u %u",&t.utime,&t.stime,&t.cutime,&t.cstime); fclose(fd);
return (t.utime + t.stime + t.cutime + t.cstime);
}
unsigned int get_cpu(pid_t p,int index)
{
unsigned int procputime; procputime = get_cpu_process_occupy(p);
std::cout<<"procputime :"<<procputime<<endl; switch(index){
case :
total_cpu_time.clear();
total_cpu_time.push_back(procputime);
break;
case :
total_cpu_time.push_back(procputime);
break;
case :
total_cpu_time.push_back(procputime);
break;
default:
DSTREAM_WARN("index is errno");
break;
}
return procputime;
}
unsigned int get_total_cpu(){
int length=total_cpu_time.size();
unsigned int total_time=;
if(length != ){
DSTREAM_WARN("get total cpu failed");
return -;
}
for(int i=;i<length;i++){
total_time+=total_cpu_time[i];
}
return total_time;
}
#ifndef __GET_MEM__
#define __GET_MEM__ #include <stdio.h>
#include <stdlib.h>
#include <iostream>
#include <unistd.h>
#include <assert.h>
#include <algorithm>
#include <vector>
#define VMRSS_LINE 15 //VMRSS line vector<int>total_memory; int get_phy_mem(const pid_t p); extern int get_mem(pid_t p);
extern int get_total_memory();
extern int get_total_mem(); #endif
//get_mem.cc
#include "get_mem.h"
int get_phy_mem(const pid_t p)
{
char file[] = {}; FILE *fd;
char line_buff[] = {};
sprintf(file,"/proc/%d/status",p); fd = fopen (file, "r");
int i;
char name[];
int vmrss;
for (i=;i<VMRSS_LINE-;i++)
{
fgets (line_buff, sizeof(line_buff), fd);
}
fgets (line_buff, sizeof(line_buff), fd);
sscanf (line_buff, "%s %d", name,&vmrss);
fclose(fd);
return vmrss;
} int get_mem(pid_t p,int index)
{
int procmemory;
promemory=get_phy_mem(p);
switch(index){
case :
total_memory.clear();
total_memory.push_back(promemory);
break;
case :
total_memory.push_back(promemory);
break; case :
total_memory.push_back(promemory);
break;
default:
DSTREAM_WARN("index is errno");
break;
}
return promemory;
} //importer+aggregater+exporter
int get_total_memory(){
int length=total_memory.size(); int total_mem=;
if(length != ){
DSTREAM_WARN("get total cpu failed");
return -;
} for(int i=;i<length;i++){
total_mem+=total_memory[i];
}
return total_mem;
} //total memory
int get_all_mem()
{
char* file = "/proc/meminfo"; FILE *fd;
char line_buff[] = {};
fd = fopen (file, "r");
int i;
char name[];
int memtotal;
fgets (line_buff, sizeof(line_buff), fd);
sscanf (line_buff, "%s %d", name,&memtotal);
fclose(fd);
return memtotal;
}

计算进程消费cpu和内存的更多相关文章

  1. .NET/C# 如何获取当前进程的 CPU 和内存占用?如何获取全局 CPU 和内存占用?

    原文:.NET/C# 如何获取当前进程的 CPU 和内存占用?如何获取全局 CPU 和内存占用? 都知道可以在任务管理器中查看进程的 CPU 和内存占用,那么如何通过 .NET 编写代码的方式来获取到 ...

  2. 如何按名称或PID查找一个进程?如何按端口号查找一个进程?如何查看一个进程的CPU和内存、文件句柄使用情况?如何查看CPU利用率高的TOP10进程清单?如何根据PID强制终止进程?

    如何按名称或PID查找一个进程?如何按端口号查找一个进程?如何查看一个进程的CPU和内存.文件句柄使用情况?如何查看CPU利用率高的TOP10进程清单? 目录 如何按名称或PID查找一个进程?如何按端 ...

  3. Linux下计算进程的CPU占用和内存占用的编程方法[转]

    from:https://www.cnblogs.com/cxjchen/archive/2013/03/30/2990548.html Linux下没有直接可以调用系统函数知道CPU占用和内存占用. ...

  4. 查看进程在CPU和内存占用的命令

    1.使用top命令 输入M表示按内存排序,也就是RES这一列从大到小排序了 它占用了3.3%的内存,用134568除以4030416结果就是3.3左右 也就是说 总物理内存是3.84GB RES这一列 ...

  5. Python测试进阶——(5)Python程序监控指定进程的CPU和内存利用率

    用Python写了个简单的监控进程的脚本monitor190620.py,记录进程的CPU利用率和内存利用率到文件pid.csv中,分析进程运行数据用图表展示. 脚本的工作原理是这样的:脚本读取配置文 ...

  6. 监控单个进程占用cpu与内存的使用情况

    #!/bin/bashinterval=1if [ "$1" != "" ]then interval=$1fiecho "检查时间间隔(单位秒):& ...

  7. zabbix监控进程的CPU和内存占用量,进程数量

    由于需要对公司特定服务进行监控,于是,通过编写脚本获取各个进程占用系统资源的信息,从而使用zabbix采集到这些数据进行特定进程的基础监控. 我这主要需要监控的程序如下: nginx redis my ...

  8. C#获取特定进程CPU和内存使用率

    首先是获取特定进程对象,可以使用Process.GetProcesses()方法来获取系统中运行的所有进程,或者使用Process.GetCurrentProcess()方法来获取当前程序所对应的进程 ...

  9. linux下统计某个进程的CPU占用和内存使用

    为了测试是否有内存泄露,写了一个监控脚本,统计这个进程的cpu和内存 主要用了 ps aux命令, 很简单,不多解释了,上脚本 #!/bin/bash # while loop CpuMemStat= ...

随机推荐

  1. 免安装版Tomcat配置内存

    去安装目录下 找 bin 目录找到这个文件 catalina.bat在文件的头部加上 set JAVA_OPTS=-Xms512m -Xmx512m -Xss1024k具体大小自己调整

  2. iOSiOS开发之退出功能(易错)

    如果,我们有两个控制器,第一个控制器是MainController,它是与Main.storyboard相关联的.第二个控制器是myController.假设myController中有一个退出按钮, ...

  3. 关于微信小程序图片失真的解决方案

    今天来说一说 关于微信小程序的图片失真问题的解决,微信小程序的image标签要设置其宽高,不然图片若宽高过大会撑开原始图片大小的区域:如下 但是宽高设置固定了会导致有些图片和规定显示图片大小的比例不一 ...

  4. 【转】air调用windows自带的虚拟键盘

    原文:http://bbs.9ria.com/blog-73243-19560.html 最近在做一个东西,需要用到虚拟键盘.刚开始准备用as3开发一套,结果突然想起来windows有个自带的虚拟键盘 ...

  5. 老李推荐:第2章2节《MonkeyRunner源码剖析》了解你的测试对象: NotePad窗口Activity之NotesList简介

    老李推荐:第2章2节<MonkeyRunner源码剖析>了解你的测试对象: NotePad窗口Activity之NotesList简介   NotePad窗口Activity之NotesL ...

  6. NPM(Node.js) 使用介绍

    前言:express 推出了4.X,自己尝试了一下,出现了各种问题.结果查看了各种文档和问题,现在在这个给大家分享下4.X版本的安装. NPM 使用介绍 NPM是随同NodeJS一起安装的包管理工具, ...

  7. HTML5技术实现Web图形图像处理——WebPhotoshop精简版

    WebPhotoshop精简版是利用HTML5技术在Web上实现对图形图像的处理,构建易维护.易共享.易于拓展.实时性的Web图形图像处理平台. 精简版功能包括:图形绘制.图像处理.图像操作.完整版包 ...

  8. Ackerman 函数 (双递归函数)

    public static int ackerman(int n,int m){  if(n==1&&m==0){return 2;}  else if(n==0&&m ...

  9. 使用spring利用HandlerExceptionResolver实现全局异常捕获

    最近一直没有时间更新是因为一直在更新自己使用的框架. 之后会慢慢带来对之前使用的spring+mvc+mybatis的优化. 会使用一些新的特性,实现一些新的功能. 我会尽量分离业务,封装好再拿出来. ...

  10. Java解决TopK问题(使用集合和直接实现)

    在处理大量数据的时候,有时候往往需要找出Top前几的数据,这时候如果直接对数据进行排序,在处理海量数据的时候往往就是不可行的了,而且在排序最好的时间复杂度为nlogn,当n远大于需要获取到的数据的时候 ...