cpu时间 / cpu利用率计算
CPU时间即反映CPU全速工作时完成该进程所花费的时间
cpu时间计算CPU TIME = (# of CPU Clock Cycles) x Clock Period // “#” 表示消耗的CPU时钟周期个数
举个多线程程序的例子,说明时间片是怎样工作的(java)
如上:
由此可见:两个线程是交替执行的(数字的变化),从宏观上(同时输出)。
以下是搜的资料:
1,什么是时间片轮转:
时间片轮转调度是一种最古老,最简单,最公平且使用最广的算法是时间片调度。每个进程被分配一个时间段,称作它的时间片,即该进程允许运行的时间。如果在
时间片结束时进程还在运行,则CPU将被剥夺并分配给另一个进程。如果进程在时间片结束前阻塞或结束,则CPU当即进行切换。调度程序所要做的就是维护一
张就绪进程列表,,当进程用完它的时间片后,它被移到队列的末尾。
时间片轮转调度中唯一有趣的一点是时间片的长度。从一个进程切换到另一个进程是需要一定时间的--保存和装入寄存器值及内存映像,更新各种表格和队列等。
假如进程切换(process switch) - 有时称为上下文切换(context switch),需要5毫秒,再假设时间片设为20毫秒,则在
做完20毫秒有用的工作之后,CPU将花费5毫秒来进行进程切换。CPU时间的20%被浪费在了管理开销上。
为了提高CPU效率,我们可以将时间片设为500毫秒。这时浪费的时间只有1%。但考虑在一个分时系统中,如果有十个交互用户几乎同时按下回车键,将发生
什么情况?假设所有其他进程都用足它们的时间片的话,最后一个不幸的进程不得不等待5秒钟才获得运行机会。多数用户无法忍受一条简短命令要5秒钟才能做出
响应。同样的问题在一台支持多道程序的个人计算机上也会发生。
结论可以归结如下:时间片设得太短会导致过多的进程切换,降低了CPU效率;而设得太长又可能引起对短的交互请求的响应变差。将时间片设为100毫秒通常是一个比较合理的折衷。
如何取得jvm实例的cpu占用
本文会贴很多代码,代码遵循Google的java代码格式。
获取数据篇
1、jmx连接的创建是一个比较重的操作,我们使用apache的common pool2创建连接工厂。
public class JmxConnectionFactory implements KeyedPooledObjectFactory<JmxServer, JMXConnector> { @Override
public PooledObject<JMXConnector> makeObject(JmxServer server) throws Exception {
JMXServiceURL
serviceURL =
new JMXServiceURL(String.format(
"service:jmx:rmi:///jndi/rmi://%s:%s/jmxrmi", server.getHost(), server.getPort()));
Map<String, Object> environment = Maps.newHashMap();
String username = server.getUsername();
String password = server.getPassword();
if ((username != null) && (password != null)) {
String[] credentials = new String[2];
credentials[0] = username;
credentials[1] = password;
environment.put(JMXConnector.CREDENTIALS, credentials);
}
environment.put("sun.rmi.transport.proxy.connectTimeout", 1000);
environment.put("sun.rmi.transport.tcp.responseTimeout", 3000);
JMXConnector connect = JMXConnectorFactory.connect(serviceURL, environment);
return new DefaultPooledObject<JMXConnector>(connect); } @Override
public void destroyObject(JmxServer key, PooledObject<JMXConnector> object) throws Exception {
object.getObject().close();
} @Override
public boolean validateObject(JmxServer key, PooledObject<JMXConnector> object) {
JMXConnector connector = object.getObject();
try {
connector.getConnectionId();
return true;
} catch (IOException exception) {
// ignore
}
return false;
} @Override
public void activateObject(JmxServer key, PooledObject<JMXConnector> p) throws Exception {
} @Override
public void passivateObject(JmxServer key, PooledObject<JMXConnector> p) throws Exception {
}
}
2、从连接池中获取JMX连接
private static GenericKeyedObjectPool<JmxServer, JMXConnector> POOL;
private static AtomicInteger actives = new AtomicInteger(0);
//....
try {
JMXConnector connector = POOL.borrowObject(server);
try {
MBeanServerConnection mbsc = connector.getMBeanServerConnection();
// 在这个地方使用连接获取JVM的监控数据
// ......
} finally {
POOL.returnObject(server, connector);
}
3、计算cpu占用的逻辑是:
获取:ProcessCpuTime,Uptime,AvailableProcessors,然后结合上一次获取到的数据得出,算式为:
Math.min(99F, (ProcessCpuTime-PreProcessCpuTime) / ((Uptime-PreUptime) * 10000F * AvailableProcessors));
方式一:通过获取相应的Bean,然后通过Bean去获取数据
private long prevUpTime, prevProcessCpuTime;
// ......
RuntimeMXBean runtimeMBean =
newPlatformMXBeanProxy(mbsc, RUNTIME_MXBEAN_NAME, RuntimeMXBean.class);
OperatingSystemMXBean
operatingSystemMBean =
newPlatformMXBeanProxy(mbsc, OPERATING_SYSTEM_MXBEAN_NAME,
com.sun.management.OperatingSystemMXBean.class);
int nCPUs = operatingSystemMBean.getAvailableProcessors();
if (runtimeMBean != null && operatingSystemMBean != null) {
long uptime = runtimeMBean.getUptime();
long processCpuTime = operatingSystemMBean.getProcessCpuTime();
if (prevUpTime != 0 && prevProcessCpuTime != 0) {
long elapsedCpu = processCpuTime - prevProcessCpuTime;
long elaspedTime = uptime - prevUpTime;
float cpuUsage = Math.min(99F, elapsedCpu / (elaspedTime * 10000F * nCPUs));
prevUpTime = uptime;
prevProcessCpuTime = processCpuTime;
//
JsonObject value = new JsonObject();
String key = "CpuUsage";
LOGGER.debug("received value '{}%' for item '{}'", cpuUsage, key);
value.addProperty(MonitorConst.JSON_TAG_VALUE, cpuUsage);
value.addProperty(MonitorConst.JSON_TAG_NAME, key);
return value;
} else {
prevUpTime = uptime;
prevProcessCpuTime = processCpuTime;
}
}
// ......
方式二、通过key来直接获取,代码通用些,比较长,代码参考zabbix gateway实现
// 通用获取方法
protected String getStringValue(MBeanServerConnection mbsc, String key) throws Exception {
MonitorItem item = new MonitorItem(key); if (item.getKeyId().equals("jmx")) {
if (2 != item.getArgumentCount()) {
throw new MonitorException(
"required key format: jmx[<object name>,<attribute name>]");
} ObjectName objectName = new ObjectName(item.getArgument(1));
String attributeName = item.getArgument(2);
String realAttributeName;
String fieldNames = "";
int sep; //
// Attribute name and composite data field names are separated by dots. On the other hand the
// name may contain a dot too. In this case user needs to escape it with a backslash. Also the
// backslash symbols in the name must be escaped. So a real separator is unescaped dot and
// separatorIndex() is used to locate it.
// sep = HelperFunctionChest.separatorIndex(attributeName); if (-1 != sep) {
LOGGER.trace("'{}' contains composite data", attributeName); realAttributeName = attributeName.substring(0, sep);
fieldNames = attributeName.substring(sep + 1);
} else {
realAttributeName = attributeName;
} // unescape possible dots or backslashes that were escaped by user
realAttributeName = HelperFunctionChest.unescapeUserInput(realAttributeName); LOGGER.trace("attributeName:'{}'", realAttributeName);
LOGGER.trace("fieldNames:'{}'", fieldNames); return getPrimitiveAttributeValue(mbsc.getAttribute(objectName, realAttributeName),
fieldNames);
} else if (item.getKeyId().equals("jmx.discovery")) {
if (0 != item.getArgumentCount()) {
throw new MonitorException("required key format: jmx.discovery");
} JsonArray counters = new JsonArray(); for (ObjectName name : mbsc.queryNames(null, null)) {
LOGGER.trace("discovered object '{}'", name); for (MBeanAttributeInfo attrInfo : mbsc.getMBeanInfo(name).getAttributes()) {
LOGGER.trace("discovered attribute '{}'", attrInfo.getName()); if (!attrInfo.isReadable()) {
LOGGER.trace("attribute not readable, skipping");
continue;
} try {
LOGGER.trace("looking for attributes of primitive types");
String
descr =
(attrInfo.getName().equals(attrInfo.getDescription()) ? null
: attrInfo
.getDescription());
findPrimitiveAttributes(counters, name, descr, attrInfo.getName(),
mbsc.getAttribute(name, attrInfo.getName()));
} catch (Exception e) {
Object[] logInfo = {name, attrInfo.getName(), e};
LOGGER.trace("processing '{},{}' failed", logInfo);
}
}
} JsonObject mapping = new JsonObject();
mapping.add(MonitorConst.JSON_TAG_DATA, counters);
return mapping.toString();
} else {
throw new MonitorException("key ID '%s' is not supported", item.getKeyId());
}
} private String getPrimitiveAttributeValue(Object dataObject, String fieldNames) throws
MonitorException {
LOGGER
.trace("drilling down with data object '{}' and field names '{}'", dataObject,
fieldNames); if (null == dataObject) {
throw new MonitorException("data object is null");
} if (fieldNames.equals("")) {
if (isPrimitiveAttributeType(dataObject.getClass())) {
return dataObject.toString();
} else {
throw new MonitorException(
"data object type is not primitive: %s" + dataObject.getClass());
}
} if (dataObject instanceof CompositeData) {
LOGGER.trace("'{}' contains composite data", dataObject); CompositeData comp = (CompositeData) dataObject; String dataObjectName;
String newFieldNames = ""; int sep = HelperFunctionChest.separatorIndex(fieldNames); if (-1 != sep) {
dataObjectName = fieldNames.substring(0, sep);
newFieldNames = fieldNames.substring(sep + 1);
} else {
dataObjectName = fieldNames;
} // unescape possible dots or backslashes that were escaped by user
dataObjectName = HelperFunctionChest.unescapeUserInput(dataObjectName); return getPrimitiveAttributeValue(comp.get(dataObjectName), newFieldNames);
} else {
throw new MonitorException("unsupported data object type along the path: %s",
dataObject.getClass());
}
} private void findPrimitiveAttributes(JsonArray counters, ObjectName name, String descr,
String attrPath, Object attribute) {
LOGGER.trace("drilling down with attribute path '{}'", attrPath); if (isPrimitiveAttributeType(attribute.getClass())) {
LOGGER.trace("found attribute of a primitive type: {}", attribute.getClass()); JsonObject counter = new JsonObject(); counter.addProperty("{#JMXDESC}", null == descr ? name + "," + attrPath : descr);
counter.addProperty("{#JMXOBJ}", name.toString());
counter.addProperty("{#JMXATTR}", attrPath);
counter.addProperty("{#JMXTYPE}", attribute.getClass().getName());
counter.addProperty("{#JMXVALUE}", attribute.toString()); counters.add(counter);
} else if (attribute instanceof CompositeData) {
LOGGER.trace("found attribute of a composite type: {}", attribute.getClass()); CompositeData comp = (CompositeData) attribute; for (String key : comp.getCompositeType().keySet()) {
findPrimitiveAttributes(counters, name, descr, attrPath + "." + key, comp.get(key));
}
} else if (attribute instanceof TabularDataSupport || attribute.getClass().isArray()) {
LOGGER.trace("found attribute of a known, unsupported type: {}", attribute.getClass());
} else {
LOGGER
.trace("found attribute of an unknown, unsupported type: {}", attribute.getClass());
}
} private boolean isPrimitiveAttributeType(Class<?> clazz) {
Class<?>[]
clazzez =
{Boolean.class, Character.class, Byte.class, Short.class, Integer.class, Long.class,
Float.class, Double.class, String.class, java.math.BigDecimal.class,
java.math.BigInteger.class,
java.util.Date.class, ObjectName.class}; return HelperFunctionChest.arrayContains(clazzez, clazz);
}
// 使用示例
获取:ProcessCpuTime,Uptime,AvailableProcessors,然后结合上一次获取到的数据得出,算式为:
String processCpuTime=getStringValue(mbsc, "jmx[\"java.lang:type=OperatingSystem\",ProcessCpuTime]")
String uptime=getStringValue(mbsc, "jmx[\"java.lang:type=Runtime\",Uptime]", #1)-last("jmx[\"java.lang:type=Runtime\",Uptime]")
String availableProcessors=getStringValue(mbsc, "jmx[\"java.lang:type=OperatingSystem\",AvailableProcessors]")
方式三、zabbix
1、clone一个Template JMX Generic,修改添加相应的item的配置,添加的Template JMX Consumer
<template>
<template>Template JMX Consumer</template>
<name>Template JMX Consumer</name>
<groups>
<group>
<name>Templates</name>
</group>
</groups>
<applications/>
<items>
<item>
<name>AvailableProcessors</name>
<type>16</type>
<snmp_community/>
<multiplier>0</multiplier>
<snmp_oid/>
<key>jmx["java.lang:type=OperatingSystem",AvailableProcessors]</key>
<delay>60</delay>
<history>7</history>
<trends>365</trends>
<status>0</status>
<value_type>3</value_type>
<allowed_hosts/>
<units/>
<delta>0</delta>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<formula>1</formula>
<delay_flex/>
<params/>
<ipmi_sensor/>
<data_type>0</data_type>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<description/>
<inventory_link>0</inventory_link>
<applications>
<application>
<name>Operating System</name>
</application>
</applications>
<valuemap/>
</item>
<item>
<name>Cpu Usage</name>
<type>15</type>
<snmp_community/>
<multiplier>0</multiplier>
<snmp_oid/>
<key>CpuUsage</key>
<delay>30</delay>
<history>7</history>
<trends>365</trends>
<status>0</status>
<value_type>0</value_type>
<allowed_hosts/>
<units>%</units>
<delta>0</delta>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<formula>1</formula>
<delay_flex/>
<params>(last("jmx[\"java.lang:type=OperatingSystem\",ProcessCpuTime]", #1)-last("jmx[\"java.lang:type=OperatingSystem\",ProcessCpuTime]", #2))/((last("jmx[\"java.lang:type=Runtime\",Uptime]", #1)-last("jmx[\"java.lang:type=Runtime\",Uptime]", #2))*10000*last("jmx[\"java.lang:type=OperatingSystem\",AvailableProcessors]", 0))</params>
<ipmi_sensor/>
<data_type>0</data_type>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<description/>
<inventory_link>0</inventory_link>
<applications>
<application>
<name>Runtime</name>
</application>
</applications>
<valuemap/>
</item>
<item>
<name>ProcessCpuTime</name>
<type>16</type>
<snmp_community/>
<multiplier>0</multiplier>
<snmp_oid/>
<key>jmx["java.lang:type=OperatingSystem",ProcessCpuTime]</key>
<delay>60</delay>
<history>7</history>
<trends>365</trends>
<status>0</status>
<value_type>3</value_type>
<allowed_hosts/>
<units/>
<delta>0</delta>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<formula>1</formula>
<delay_flex/>
<params/>
<ipmi_sensor/>
<data_type>0</data_type>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<description/>
<inventory_link>0</inventory_link>
<applications>
<application>
<name>Operating System</name>
</application>
</applications>
<valuemap/>
</item>
</items>
<discovery_rules/>
<macros/>
<templates>
<template>
<name>Template JMX Generic</name>
</template>
</templates>
<screens/>
</template>
// 修改原来的模板
<item>
<name>jvm Uptime</name>
<type>15</type>
<snmp_community/>
<multiplier>1</multiplier>
<snmp_oid/>
<key>jmxUptime</key>
<delay>60</delay>
<history>7</history>
<trends>365</trends>
<status>0</status>
<value_type>3</value_type>
<allowed_hosts/>
<units>uptime</units>
<delta>0</delta>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<formula>0.001</formula>
<delay_flex/>
<params>jmx["java.lang:type=Runtime",Uptime]</params>
<ipmi_sensor/>
<data_type>0</data_type>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<description/>
<inventory_link>0</inventory_link>
<applications>
<application>
<name>Runtime</name>
</application>
</applications>
<valuemap/>
</item>
<item>
<name>jvm Uptime Microsecond</name>
<type>16</type>
<snmp_community/>
<multiplier>0</multiplier>
<snmp_oid/>
<key>jmx["java.lang:type=Runtime",Uptime]</key>
<delay>60</delay>
<history>7</history>
<trends>365</trends>
<status>0</status>
<value_type>3</value_type>
<allowed_hosts/>
<units>uptime</units>
<delta>0</delta>
<snmpv3_contextname/>
<snmpv3_securityname/>
<snmpv3_securitylevel>0</snmpv3_securitylevel>
<snmpv3_authprotocol>0</snmpv3_authprotocol>
<snmpv3_authpassphrase/>
<snmpv3_privprotocol>0</snmpv3_privprotocol>
<snmpv3_privpassphrase/>
<formula>1</formula>
<delay_flex/>
<params/>
<ipmi_sensor/>
<data_type>0</data_type>
<authtype>0</authtype>
<username/>
<password/>
<publickey/>
<privatekey/>
<port/>
<description/>
<inventory_link>0</inventory_link>
<applications>
<application>
<name>Runtime</name>
</application>
</applications>
<valuemap/>
</item>
cpu时间 / cpu利用率计算的更多相关文章
- Linux下如何查看高CPU占用率线程 LINUX CPU利用率计算
目录(?)[-] proc文件系统 proccpuinfo文件 procstat文件 procpidstat文件 procpidtasktidstat文件 系统中有关进程cpu使用率的常用命令 ps ...
- 墙上时钟时间 ,用户cpu时间 ,系统cpu时间
一. 墙上时钟时间 ,用户cpu时间 ,系统cpu时间定义与联系 时钟时间(墙上时钟时间wall clock time):从进程从开始运行到结束,时钟走过的时间,这其中包含了进程在阻塞和等待状态的时间 ...
- CPU利用率和CPU负荷(CPU usage vs CPU load)
对于CPU的性能监测,通常用top指令能显示出两个指标:cpu 利用率和cpu负荷. 其中%Cpu相关的内容: us表示用户进程cpu利用率,sy表示系统内核进程cpu利用率,ni表示运行正常进程消耗 ...
- 【转载】Java垃圾回收内存清理相关(虚拟机书第三章),GC日志的理解,CPU时间、墙钟时间的介绍
主要看<深入理解Java虚拟机> 第三张 P84 开始是垃圾收集相关. 1. 1960年诞生于MIT的Lisp是第一门采用垃圾回收的语言. 2. 程序计数器.虚拟机栈.本地方法栈3个区域随 ...
- SQL Server CPU时间和占用时间及优化
如何测试sql语句执行时间 在MSSQL Server中通过查看SQL语句执行所用的时间,来衡量SQL语句的性能. set statistics profile on set statistics i ...
- cpu,io密集型计算概念
I/O密集型 (CPU-bound) I/O bound 指的是系统的CPU效能相对硬盘/内存的效能要好很多,此时,系统运作,大部分的状况是 CPU 在等 I/O (硬盘/内存) 的读/写,此时 CP ...
- CPU使用率原理及计算方式
本文转载自CPU使用率原理及计算方式 CPU:超线程和多核 超线程(Hyper-Threading ) 超线程是Intel最早提出一项技术,最早出现在2002年的Pentium4上.单个采用超线程的C ...
- 分享自己做的一个指定进程以及线程长时间cpu监控的工具
前言: 前面给大家分享过一个工作中用到的编译拷贝脚本,其实工作中还有一些其他工具的使用,今天再来分享一个自己纯手工的CPU监控的脚本.大家可以结合上篇文章与本篇文章一起学习shell. 主要实现功能: ...
- 简析 Linux 的 CPU 时间
从 CPU 时间说起... 下面这个是 top 命令的界面,相信大家应该都不陌生. top - 19:01:38 up 91 days, 23:06, 1 user, load average: 0. ...
随机推荐
- ActiveMQ 认证(一)
新搭建的ActiveMQ服务,在发布和读取消息时,连接的权限为ActiveMQConnection.DEFAULT_USER和ActiveMQConnection.DEFAULT_PASSWORD. ...
- Python开发基础-Day16import模块导入和包的调用
模块概念 在Python中,一个.py文件就称之为一个模块(Module).使用模块组织代码,最大的好处是大大提高了代码的可维护性 模块一共三种:python标准库.第三方模块.应用程序自定义模块. ...
- css-移动&缩放元素
transform 属性向元素应用 2D 或 3D 转换.该属性允许我们对元素进行旋转.缩放.移动或倾斜. 用法:object.style.transform="rotate(7deg)&q ...
- 【BZOJ 3530】【SDOI 2014】数数
http://www.lydsy.com/JudgeOnline/problem.php?id=3530 上午gty的测试题,爆0了qwq 类似文本生成器那道题,把AC自动机的转移建出来,准确地说建出 ...
- CodeForces - 1000E We Need More Bosses
题面在这里! 依然一眼题,求出割边之后把图缩成一棵树,然后直接求最长链就行了2333 #include<bits/stdc++.h> #define ll long long using ...
- 【POJ】1088滑雪
滑雪 Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 97335 Accepted: 36911 Description ...
- springmvc poi实现报表导出
1.pom文件: <dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</ ...
- ConcurrentHashMap(Java8)源码分析
1. 常量.成员变量 private static final int MAXIMUM_CAPACITY = 1 << 30; // 和HashMap一样 private static f ...
- 配置友盟最新SDK遇到的问题
编译报错 Undefined symbols for architecture i386:原因:i386是代表模拟器,显示i386错误说明静态库不支持模拟器,只支持真机.友盟最新SDK可能不支持模拟 ...
- [转]SQL Server 2008支持将数据导出为脚本
本文转自:http://blog.csdn.net/studyzy/article/details/4303759 以前我们要将一个表中的数据导出为脚本,那么只有在网上找一个导出数据的Script,然 ...