0

In my application I get the estimated memory taken by the process from another application. But I am looking to get the exact memory required by the processor to run.

As I am searching online on how to get the correct memory required by the process, I found oshi lib does that. But I didn't find the the way to implement the solution. Can anyone please help me?

OSHI lib: https://github.com/oshi/oshi

FYI: We use OSHI lib to get the systemInfo, hardware, os, centralProcessor and global memory. Below is the code snippet.

    oshi.SystemInfo systemInfo = new oshi.SystemInfo();
    this.hal = systemInfo.getHardware();
    this.os = systemInfo.getOperatingSystem();
    this.centralProcessor = this.hal.getProcessor();
    this.globalMemory = this.hal.getMemory();
4

2 回答 2

1
public static void memoryUtilizationPerProcess(int pid) {
        /**
         * Resident Size : how much memory is allocated to that process and is in RAM
         */
        OSProcess process;
        SystemInfo si = new SystemInfo();
        OperatingSystem os = si.getOperatingSystem();
        process = os.getProcess(pid);
        oshi.hardware.GlobalMemory globalMemory = si.getHardware().getMemory();
        long usedRamProcess = process.getResidentSetSize();
        long totalRam = globalMemory.getTotal();
        double res1 = (double) ((usedRamProcess*100)/totalRam);
        System.out.println("\nMemory Usage :");
        System.out.println("Memory(Ram Used/Total Mem)="+res1+"%");
        System.out.println("Resident Size: "+humanReadableByteCountBin(usedRamProcess));
        System.out.println("Total Size: "+humanReadableByteCountBin(totalRam));

    }

 public static String humanReadableByteCountBin(long bytes) {
        long absB = bytes == Long.MIN_VALUE ? Long.MAX_VALUE : Math.abs(bytes);
        if (absB < 1024) {
            return bytes + " B";
        }
        long value = absB;
        CharacterIterator ci = new StringCharacterIterator("KMGTPE");
        for (int i = 40; i >= 0 && absB > 0xfffccccccccccccL >> i; i -= 10) {
            value >>= 10;
            ci.next();
        }
        value *= Long.signum(bytes);
        return String.format("%.1f %ciB", value / 1024.0, ci.current());
    }
于 2020-09-24T12:27:58.140 回答
1

也许从OSProcess类中检索内存使用情况:

OSProcess process =  new SystemInfo().getHardware().getOperatingSystem().getProcess(myPid);
process.getVirtualSize();
process.getResidentSetSize();
于 2019-04-29T17:29:22.927 回答