通过oshi这个三方库来获取,目前这个最准确。

引入依赖

<dependency><groupId>com.github.oshi</groupId><artifactId>oshi-core</artifactId><version>3.5.0</version></dependency>

Demo代码


import oshi.SystemInfo;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
import oshi.util.FormatUtil;import java.lang.management.ManagementFactory;
import java.lang.management.RuntimeMXBean;public class Test {public static void main(String[] args) {ExecutorService service =  Executors.newSingleThreadScheduledExecutor();final long[] bytesWritten = {0};final long[] bytesRead = {0};service.execute(new Runnable() {@SneakyThrows@Overridepublic void run() {while(true) {SystemInfo systemInfo = new SystemInfo();OperatingSystem os = systemInfo.getOperatingSystem();int processId = os.getProcessId();OSProcess process = os.getProcess(processId);long curBytesWritten = process.getBytesWritten();long curBytesRead = process.getBytesRead();if (bytesWritten[0] == 0 ){bytesWritten[0] = curBytesWritten;}if (bytesRead[0] == 0 ){bytesRead[0] = curBytesRead;}log.info("pid %d 当前进程:占用内存 %s | 占用CPU(%%) %.2f | 写入(bytes) %d | 读取(bytes) %d".formatted(processId, FormatUtil.formatBytes(process.getResidentSetSize()), getProcessCpuLoad(),curBytesWritten - bytesWritten[0],curBytesRead - bytesRead[0]));bytesWritten[0] = curBytesWritten;bytesRead[0] = curBytesRead;try {Thread.sleep(1000);} catch (InterruptedException e) {log.error("性能监控时出现异常:{}",e);}}}});}/*** 获取当前进程的CPU利用率* @return* @throws Exception*/public static double getProcessCpuLoad() throws Exception {MBeanServer mbs    = ManagementFactory.getPlatformMBeanServer();ObjectName name    = ObjectName.getInstance("java.lang:type=OperatingSystem");AttributeList list = mbs.getAttributes(name, new String[]{ "ProcessCpuLoad" });if (list.isEmpty()) {return Double.NaN;}Attribute att = (Attribute)list.get(0);Double value  = (Double)att.getValue();// usually takes a couple of seconds before we get real valuesif (value == -1.0) {return Double.NaN;}// returns a percentage value with 1 decimal point precisionreturn ((int)(value * 1000) / 10.0);}
}

效果图

如果还想对这些数据进行统计的话,我这里也写了个小DEMO,用于解析日志文件,然后计算出下面这些指标:

平均RAM使用(MB)548.36 | 总CPU利用率(%) 12.70 | 平均写入速率(kb/s) 713 | 平均读取速率(kb/s) 346
最大RAM使用(MB)838.40 | 最大CPU利用率(%) 25.20 | 最大写入速率(kb/s) 8161 | 最大读取速率(kb/s) 65582

需要注意,执行代码前要修改日志所在路径folderPath ,以及日志持续时间durationSeconds

DEMO代码

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;public class Test {public static void main(String[] args) {// 定义指定文件夹路径String folderPath = "D:\\xx\\logs\\Info\\日志";File folder = new File(folderPath);// 遍历文件夹下所有文件int countFile = 1;//持续时间double durationSeconds = 2271;double totalRAMUseage = 0d;double maxRAMUseage = 0d;double totalCPUUseage = 0d;double maxCPUUseage = 0d;long maxReadBytes = 0;long totalReadBytes = 0;long maxWrittenBytes = 0;long totalWrittenBytes = 0;File[] files = folder.listFiles((d, name) -> name.endsWith(".info"));// 使用自定义的Comparator按照创建时间从早到晚排序Arrays.sort(files, Comparator.comparingLong(File::lastModified));for (File file: files) {if (file.isFile() && file.getName().endsWith(".info")) {// 打开文件并按行读取try (BufferedReader br = new BufferedReader(new FileReader(file))) {System.out.println("正在解析日志%s(%d/%d)".formatted(file.getName(),countFile++,folder.listFiles().length));String line;while ((line = br.readLine()) != null) {if (line.contains("占用内存")) {double ramUsage = getRAMUsageAfterSpecifiedString(line);double cpuUsage = getCPUUsageAfterSpecifiedString(line);long readBytes = getReadBytesAfterSpecifiedString(line);long writtenBytes = getWrittenBytesAfterSpecifiedString(line);if (ramUsage > maxRAMUseage){System.out.println("max ram "+line);}if (cpuUsage > maxCPUUseage){System.out.println("max cpu "+line);}if (readBytes > maxReadBytes){System.out.println("max read "+line);}if (writtenBytes > maxWrittenBytes){System.out.println("max write "+line);}maxRAMUseage = (ramUsage > maxRAMUseage ? ramUsage : maxRAMUseage);maxCPUUseage = (cpuUsage > maxCPUUseage ? cpuUsage : maxCPUUseage);maxReadBytes = (readBytes > maxReadBytes ? readBytes : maxReadBytes);maxWrittenBytes = (writtenBytes > maxWrittenBytes ? writtenBytes : maxWrittenBytes);totalRAMUseage += ramUsage;totalCPUUseage += cpuUsage;totalReadBytes += readBytes;totalWrittenBytes += writtenBytes;}}} catch (IOException e) {e.printStackTrace();}}}System.out.println("平均RAM使用(MB)%.2f | 总CPU利用率(%%) %.2f | 平均写入速率(kb/s) %d | 平均读取速率(kb/s) %d ".formatted(totalRAMUseage / durationSeconds,totalCPUUseage/ durationSeconds,totalWrittenBytes / (long)durationSeconds/1024,totalReadBytes/(long)durationSeconds/1024));System.out.println("最大RAM使用(MB)%.2f | 最大CPU利用率(%%) %.2f | 最大写入速率(kb/s) %d | 最大读取速率(kb/s) %d ".formatted(maxRAMUseage,maxCPUUseage,maxWrittenBytes/1024,maxReadBytes/1024));}public static double getRAMUsageAfterSpecifiedString(String specifiedString){// 定义待匹配的字符串// 定义正则表达式String patternString = ".*占用内存 (\\d+\\.\\d+) GiB.*";Pattern pattern = Pattern.compile(patternString);// 进行匹配Matcher matcher = pattern.matcher(specifiedString);if (matcher.matches()) {// 获取第一组匹配到的数字String numberStr = matcher.group(1);return Double.parseDouble(numberStr)*1024;}else {patternString = ".*占用内存 (\\d+\\.\\d+) MiB.*";pattern = Pattern.compile(patternString);// 进行匹配matcher = pattern.matcher(specifiedString);if (matcher.matches()) {// 获取第一组匹配到的数字String numberStr = matcher.group(1);return Double.parseDouble(numberStr);}}return 0d;}public static double getCPUUsageAfterSpecifiedString(String specifiedString){// 定义待匹配的字符串// 定义正则表达式String patternString = ".*占用CPU\\(%\\) (\\d+\\.\\d+).*";Pattern pattern = Pattern.compile(patternString);// 进行匹配Matcher matcher = pattern.matcher(specifiedString);if (matcher.matches()) {// 获取第一组匹配到的数字String numberStr = matcher.group(1);return Double.parseDouble(numberStr);}return 0d;}public static long getReadBytesAfterSpecifiedString(String specifiedString){// 定义待匹配的字符串// 定义正则表达式String patternString = ".*读取\\(bytes\\) (\\d+).*";Pattern pattern = Pattern.compile(patternString);// 进行匹配Matcher matcher = pattern.matcher(specifiedString);if (matcher.matches()) {// 获取第一组匹配到的数字String numberStr = matcher.group(1);return Long.parseLong(numberStr);}return 0;}public static long getWrittenBytesAfterSpecifiedString(String specifiedString){// 定义待匹配的字符串// 定义正则表达式String patternString = ".*写入\\(bytes\\) (\\d+).*";Pattern pattern = Pattern.compile(patternString);// 进行匹配Matcher matcher = pattern.matcher(specifiedString);if (matcher.matches()) {// 获取第一组匹配到的数字String numberStr = matcher.group(1);return Long.parseLong(numberStr);}return 0;}}

JAVA获取当前进程的内存占用数和CPU利用率以及读写字节数并计算统计信息相关推荐

  1. ubuntu查看内存占用和查看cpu使用情况的简单方法(ubuntu内存管理)

    单独查看内存使用情况的命令:free -m 查看内存及cpu使用情况的命令:top 也可以安装htop工具,这样更直观, 安装命令如下:sudo apt-get install htop 安装完后,直 ...

  2. 高内存占用或高CPU占解决办法

    服务性能排查一般就两种:高内存占用或高CPU占用,需要具体问题具体分析.比如应用程序高内存占用,可能因为大文件读取.频繁IO,内存消耗频繁,导致频繁GC,进一步占用内存和CPU:比如应用程序高CPU占 ...

  3. Shell - 监控某个进程的内存占用情况、主机CPU、磁盘空间等信息以及守护进程

    文章目录 脚本 启动的两种方式 方式一 注册到系统Cron 方式二 运行结果 linux内存.cpu.磁盘IO 脚本 #!/bin/sh ############################## ...

  4. python统计httpd 进程的内存占用百分比

    本文结构: 介绍用命令行如何统计内存占用百分比 介绍用python 如何通过读取进程文件,统计进程的内存总大小,然后计算占系统内存的百分比 第一部分: 在linux 下,统计apache 进程的内存使 ...

  5. 一步步优化JVM四:决定Java堆的大小以及内存占用

    到目前为止,还没有做明确的优化工作.只是做了初始化选择工作,比如说:JVM部署模型.JVM运行环境.收集哪些垃圾回收器的信息以及需要遵守垃圾回收原则.这一步将介绍如何评估应用需要的内存大小以及Java ...

  6. JVM优化:决定Java堆的大小以及内存占用

    转载:https://blog.csdn.net/zhoutao198712/article/details/7783070    到目前为止,还没有做明确的优化工作.只是做了初始化选择工作,比如说: ...

  7. java获取所有进程_Java 获取系统的进程列表

    前几天发表了<Java 定时启动服务>文章,现在发表这篇文档<Java 获取系统的进程列表>,看似联系不大,实质在某些需求上还是有所关系.比如现在有这个需求:定时器启动服务时, ...

  8. 监控进程的内存占用,CPU消耗,并将结果写入csv文件中

    #!/bin/bash #写入表头,日期.时间.内存占用.CPU echo "date,time,RES,%CPU" > cpu_test.csv #定义进程号 pid=1 ...

  9. 进程的内存占用情况分析

    我们都知道进程运行时,会有一个栈空间(stack)和一个堆空间(heap), 栈空间用于函数调用和局部变量,堆空间是C语言的 malloc 来分配的全局指针.这些都是进程的私有数据,除了这些,还有映射 ...

最新文章

  1. Asp.net支持的最大上传文件大小
  2. Win64 驱动内核编程-3.内核里使用内存
  3. 对NUnitAddIn做了下修改
  4. 关于颜色值透明度的设置
  5. junit单体测试(PowerMockito)一
  6. 数据结构栈和队列的实现
  7. win32开发(鼠标)
  8. (分治)分治法 及 题目
  9. 安装mujoco报错:distutils.errors.DistutilsExecError: command ‘gcc‘ failed with exit status 1
  10. 南充高中计算机老师,2021四川南充教师招聘考试高中信息技术说课稿之《表格的装饰》...
  11. ubuntu中使用.rpm
  12. excel按季度分类汇总_巧用excel进行分类汇总的五种方法
  13. Unirech腾讯云国际站代充-云服务器系统盘使用问题
  14. C语言基础学习——第1天(类型+操作符)
  15. oracle000936,奇怪的ORA-000936错误
  16. PCB抄板原理图常见错误
  17. 期盼小豆发芽(2008.7.20)
  18. Vulkan spec 中文版 翻译基础版本切换
  19. 标准版服务器配置文件是哪个,T+12.0标准版的服务器配置是什么样的??
  20. 自媒体百家号指数低怎么办,其实提高指数很容易

热门文章

  1. iocp(完成端口)采用WSARecv WSASend处理数据,WSASend群发(广播)消息
  2. 基于智慧灯杆的智慧社区解决方案,看看智慧灯杆到底能做什么?
  3. 百度云空间极速秒传是什么原理?
  4. 2014年YY公开课录像-韦东山-专题视频课程
  5. OA系统:实现员工签到表导出xls
  6. 栈的介绍 什么是栈?
  7. BTA | 朱佩江:Pallet项目,“细腰”链通互联网价值体系
  8. 加载项inprivate_如何在Internet Explorer的Metro版本中打开InPrivate选项卡
  9. ad设置塞孔_PCB线路板导电孔塞孔工艺的实现
  10. 高温来袭?通过python爬虫爬取天气预警信息