I've been investigating the best approach to achieve the following data for a specific process:
- CPU usage
- Memory usage
- Disk usage
- Network usage
I decided to go with OSHI (Operating system & hardware information) API. Unfortunate for me , this API isn't giving me the desired info out of the box, it requires some basic knowledge of how to calculate , for example the cpu usage per process.
My Question is: How can I get the memory, disk, network usage by process id ?
using the following example of cpu usage data per prcoess
For example:
To get the actual CPU usage of a claculator.exe running process:
import oshi.SystemInfo;
import oshi.hardware.CentralProcessor;
import oshi.software.os.OSProcess;
import oshi.software.os.OperatingSystem;
public class processCPUusage {
public static void main(String[] args) throws InterruptedException {
OSProcess process;
long currentTime,previousTime = 0,timeDifference;
double cpu;
int pid = 7132;
SystemInfo si = new SystemInfo();
OperatingSystem os = si.getOperatingSystem();
CentralProcessor processor = si.getHardware().getProcessor();
int cpuNumber = processor.getLogicalProcessorCount();
boolean processExists = true;
while (processExists) {
process = os.getProcess(pid); // calculator.exe process id
if (process != null) {
// CPU
currentTime = process.getKernelTime() + process.getUserTime();
if (previousTime != -1) {
// If we have both a previous and a current time
// we can calculate the CPU usage
timeDifference = currentTime - previousTime;
cpu = (100d * (timeDifference / ((double) 1000))) / cpuNumber;
System.out.println(cpu);
}
previousTime = currentTime;
Thread.sleep(1000);
} else {
processExists = false;
}
}
}
}
The framework I'm using https://github.com/oshi/oshi/tree/master/src/site/markdown demonstrates the desired functionality but lacks proper examples
- Language: Java 8
- Build tool: Maven 2
- OS: Windows 10*
OSHI library + slf4j
<dependency>
<groupId>com.github.dblock</groupId>
<artifactId>oshi-core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-api</artifactId>
<version>1.7.5</version>
</dependency>
<dependency>
<groupId>org.slf4j</groupId>
<artifactId>slf4j-log4j12</artifactId>
<version>1.7.5</version>
</dependency>