当前位置:   article > 正文

Java获取任务管理器内存、各磁盘内存、CPU使用率数据_java获取cpu使用率

java获取cpu使用率

1、获取任务管理器运行内存、各磁盘内存

1.代码实现:

    /**
     * 获取内存使用情况
     */
    public static void getMemory() throws IOException {
        OperatingSystemMXBean mem = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
        // 获取内存总容量
        long totalMemorySize = mem.getTotalPhysicalMemorySize();
        // 获取可用内存容量(剩余物理内存)
        long freeMemorySize = mem.getFreePhysicalMemorySize();
        // 空闲的交换容量
        long freeSwapSpaceSize = mem.getFreeSwapSpaceSize();

        float usedRAM = (float)(((totalMemorySize - freeMemorySize) * 1.0 / totalMemorySize) * 100);

        System.out.println("物理内存总容量totalMemorySize:" + transformation(totalMemorySize) );
        System.out.println("剩余物理内存可用容量freeMemorySize:" + transformation(freeMemorySize));
        System.out.println("usedRAM:" + usedRAM);
        System.out.println("空闲的交换容量:" + transformation(freeSwapSpaceSize));

        Runtime runtime = Runtime.getRuntime();
        // java虚拟机中的内存总量,可用内存空间 单位为byte,默认为系统的1/64
        long totalMemory = runtime.totalMemory();
        // java虚拟机试图使用的最大内存量 最大可用内存空间 单位byte,默认为系统的1/4
        long maxMemory = runtime.maxMemory();
        // java 虚拟机中的空闲内存量 空闲空间 单位byte, 默认为系统的1/4
        long freeMemory = runtime.freeMemory();
        float usedRAMJava = (float)(((totalMemory - freeMemory) * 1.0 / totalMemory) * 100);
        System.out.println("java虚拟机中的内存总量:" + totalMemory / 1024 / 1024 + "MB" );
        System.out.println("java虚拟机试图使用的最大内存量:" + maxMemory / 1024 / 1024 + "MB" );
        System.out.println("java虚拟机中的空闲内存量:" + freeMemory / 1024 / 1024 + "MB" );
        System.out.println("java虚拟机中的剩余内存占总量:" + usedRAMJava + "%" );

        DecimalFormat df = new DecimalFormat("#0.00");
        File[] disks = File.listRoots();
        for (File file : disks) {
            // 获取盘符
            System.out.print(file.getCanonicalPath() + "   ");
            // 获取总容量
            long totalSpace = file.getTotalSpace();
            // 获取剩余容量
            long usableSpace = file.getUsableSpace();
            // 获取已经使用的容量
            long freeSpace = totalSpace - usableSpace;
            // 获取使用率
            float useRate = (float)((freeSpace * 1.0 / totalSpace) * 100);
            System.out.print("总容量: " + transformation(totalSpace));
            System.out.print("已经使用: " + transformation(freeSpace));
            System.out.print("剩余容量: " + transformation(usableSpace));
            System.out.println("使用率: " + Double.parseDouble(df.format(useRate)) + "%   ");
        }
    }
    /**
     * 将字节容量转化为GB
     */
    public static String transformation(long size){
        return (float) size / 1024 / 1024 / 1024 + "GB"+"   ";
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57

2.运行结果
在这里插入图片描述

3.任务管理器

在这里插入图片描述

2、获取CPU使用率

通过Java获取CPU使用率,搜索大多方法都是使用getSystemCpuLoad()来获取,具体代码如下:

	public void getCpu() {
	        OperatingSystemMXBean mem = (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
	        System.out.println("CPU使用率:" + mem.getSystemCpuLoad());
	        System.out.println("进程占用CPU:" + mem.getProcessCpuLoad());
	}
  • 1
  • 2
  • 3
  • 4
  • 5

代码结果如下:
在这里插入图片描述
问题:为什么获取的CPU使用率是0.0?而且在其他电脑上还出现了getSystemCpuLoad和getProcessCpuLoad获取的都为-1(负数)的情况?

经过多次搜索,大概看到的解析是说跟JDK的版本有关系,或者是跟电脑本身无权限访问的原因(未求证)。

思路转换,寻找其他方法:
CPU使用率是如下图任务管理器中利用率的百分比:
在这里插入图片描述
还可以通过cmd终端窗口查看CPU使用率,cmd命令如下:

# 一秒中输出一次
typeperf "processor(_total)\% processor time"

# 若是只要执行一次,末尾添加  -sc 1, 或 -sc 次数
typeperf "processor(_total)\% processor time" -sc 1
  • 1
  • 2
  • 3
  • 4
  • 5

执行结果:
在这里插入图片描述
在这里插入图片描述
其次还可使用wmic命令,根据搜索loadpercentage也代表CPU利用率

wmic cpu get loadpercentage
  • 1

运行结果:
在这里插入图片描述
即,想要通过Java获取CPU的使用率就可以用Runtime.getRuntime().exec()调用终端窗口cmd执行相应命令,实现代码如下所示:

    public static int getCpuUseRatio() {
        Process process = null;
        BufferedReader bufferedReader = null;
        try {
            String CMD_PYTHON = "wmic cpu get loadpercentage";
            process = Runtime.getRuntime().exec(CMD_PYTHON);
            bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream(), Charset.forName("GBK")));
            String res;
            while ((res = bufferedReader.readLine()) != null) {
                String strs = res.trim();  // 去除输出发前后空格
                if (!"".equals(strs) && !"LoadPercentage".equals(strs)) {
                    return Integer.parseInt(strs);
                }
            }
            bufferedReader.close();
            process.destroy();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (bufferedReader != null){
                    bufferedReader.close();
                }
            } catch (IOException ioException) {
                ioException.printStackTrace();
            }
            if (process != null) {
                process.destroy();
            }
        }
        // 获取失败,或出现异常
        return -1;
    }
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号