【JAVA】获取windows内存使用率排名前十的进程信息、总的cpu和内存使用率

代码

java 复制代码
package sample.appfunction;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.*;

class ProcessInfo implements Comparable<ProcessInfo> {
    String name;
    long memoryUsage;
    String pid;

    public ProcessInfo(String pid,String name, long memoryUsage) {
        this.name = name;
        this.memoryUsage = memoryUsage;
        this.pid=pid;
    }

    @Override
    public int compareTo(ProcessInfo other) {
        // 按内存使用量降序排序
        return Long.compare(other.memoryUsage, this.memoryUsage);
    }
}

public class tt {
    public static void main(String[] args) {
        try {
            // 获取 CPU 使用率
            double cpuUsage = getCPUUsage();
            System.out.printf("CPU 使用率: %.2f%%%n", cpuUsage);

            // 获取内存使用率
            double memoryUsage1 = getMemoryUsage();
            System.out.printf("内存使用率: %.2f%%%n", memoryUsage1);
            
            
            // 执行 wmic 命令获取进程内存使用信息
            //cdm使用的命令:wmic process get ProcessId,Name,WorkingSetSize,ParentProcessId /format:csv
            ProcessBuilder processBuilder = new ProcessBuilder("wmic", "process", "get", "ProcessId,Name,WorkingSetSize", "/format:csv");
            Process process = processBuilder.start();

            BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
            String line;
            List<ProcessInfo> processInfos = new ArrayList<>();

            // 跳过标题行
            reader.readLine();

            while ((line = reader.readLine()) != null) {
                if (!line.isEmpty()) {
                    //line:LWX1000405,chrome.exe,1332492,94793728(用户,进程名,pid,用量)
                    String[] parts = line.split(",");
                    if (parts.length >= 4) {
                        String name = parts[1];
                        String pid=parts[2];
                        try {
                            long memoryUsage = Long.parseLong(parts[3].trim());
                            processInfos.add(new ProcessInfo(pid,name, memoryUsage));
                        } catch (NumberFormatException e) {
                            // 忽略无法解析的行
                        }
                    }
                }
            }

            // 按内存使用量排序
            Collections.sort(processInfos);

            // 输出排名前 10 的进程
            System.out.println("内存使用率排名前 10 的进程:");
            for (int i = 0; i < Math.min(10, processInfos.size()); i++) {
                ProcessInfo info = processInfos.get(i);
                System.out.printf("%d. PID:%S 进程名: %s, 内存使用量: %.2f MB%n",
                        i + 1,info.pid, info.name, (double) info.memoryUsage / (1024 * 1024));
            }


        } catch (IOException | InterruptedException e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取 CPU 使用率
     * @return CPU 使用率百分比
     * @throws IOException 执行命令时可能抛出的异常
     * @throws InterruptedException 进程等待时可能抛出的异常
     */
    public static double getCPUUsage() throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec("wmic cpu get loadpercentage");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        while ((line = reader.readLine()) != null) {
            if (!line.isEmpty() && !line.contains("LoadPercentage")) {
                try {
                    return Double.parseDouble(line.trim());
                } catch (NumberFormatException e) {
                    return 0;
                }
            }
        }
        return 0;
    }

    /**
     * 获取内存使用率
     * @return 内存使用率百分比
     * @throws IOException 执行命令时可能抛出的异常
     * @throws InterruptedException 进程等待时可能抛出的异常
     */
    public static double getMemoryUsage() throws IOException, InterruptedException {
        Process process = Runtime.getRuntime().exec("wmic OS get FreePhysicalMemory,TotalVisibleMemorySize /Value");
        BufferedReader reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
        String line;
        long totalMemory = 0;
        long freeMemory = 0;
        while ((line = reader.readLine()) != null) {
            if (line.startsWith("TotalVisibleMemorySize")) {
                totalMemory = Long.parseLong(line.split("=")[1].trim());
            } else if (line.startsWith("FreePhysicalMemory")) {
                freeMemory = Long.parseLong(line.split("=")[1].trim());
            }
        }
        if (totalMemory > 0) {
            return (1 - (double) freeMemory / totalMemory) * 100;
        }
        return 0;
    }
}

输出

CPU 使用率: 78.00%

内存使用率: 87.50%

内存使用率排名前 10 的进程:

  1. PID:18744 进程名: chrome.exe, 内存使用量: 2828.82 MB
  2. PID:20844 进程名: idea64.exe, 内存使用量: 2077.74 MB
  3. PID:316564 进程名: java.exe, 内存使用量: 1199.97 MB
  4. PID:1329312 进程名: java.exe, 内存使用量: 970.99 MB
  5. PID:10552 进程名: chrome.exe, 内存使用量: 461.88 MB
  6. PID:1325292 进程名: chrome.exe, 内存使用量: 452.34 MB
  7. PID:17388 进程名: IM.exe, 内存使用量: 442.53 MB
  8. PID:15832 进程名: chrome.exe, 内存使用量: 291.07 MB
  9. PID:1345224 进程名: chrome.exe, 内存使用量: 272.21 MB
  10. PID:1342028 进程名: java.exe, 内存使用量: 264.14 MB
相关推荐
QX_hao11 小时前
【Go】--map和struct数据类型
开发语言·后端·golang
你好,我叫C小白11 小时前
C语言 循环结构(1)
c语言·开发语言·算法·while·do...while
无妄无望11 小时前
docker学习(4)容器的生命周期与资源控制
java·学习·docker
MC丶科12 小时前
【SpringBoot 快速上手实战系列】5 分钟用 Spring Boot 搭建一个用户管理系统(含前后端分离)!新手也能一次跑通!
java·vue.js·spring boot·后端
千码君201612 小时前
React Native:从react的解构看编程众多语言中的解构
java·javascript·python·react native·react.js·解包·解构
淮北49412 小时前
windows安装minicoda
windows·python·conda
夜白宋13 小时前
【word多文档docx合并】
java·word
Evand J13 小时前
【MATLAB例程】基于USBL和DVL的线性回归误差补偿,对USBL和DVL导航数据进行相互补偿,提高定位精度,附代码下载链接
开发语言·matlab·线性回归·水下定位·usbl·dvl
@yanyu66613 小时前
idea中配置tomcat
java·mysql·tomcat
2501_9167665413 小时前
【项目部署】JavaWeb、MavenJavaWeb项目部署至 Tomcat 的实现方式
java·tomcat