Reputation: 101
For example in linux htop: http://scr.hu/1det/r1ghl and when I check in my application cpu usage by pid: 27914 it should print me 51%. How to this do?
public static int calcCPU(long cpuStartTime, long elapsedStartTime, int cpuCount) {
long end = System.nanoTime();
long totalAvailCPUTime = cpuCount * (end - elapsedStartTime);
long totalUsedCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime() - cpuStartTime;
//log("Total CPU Time:" + totalUsedCPUTime + " ns.");
//log("Total Avail CPU Time:" + totalAvailCPUTime + " ns.");
float per = ((float) totalUsedCPUTime * 100) / (float) totalAvailCPUTime;
log(per);
return (int) per;
}
static boolean isPrime(int n) {
// 2 is the smallest prime
if (n <= 2) {
return n == 2;
}
// even numbers other than 2 are not prime
if (n % 2 == 0) {
return false;
}
// check odd divisors from 3
// to the square root of n
for (int i = 3, end = (int) Math.sqrt(n); i <= end; i += 2) {
if (n % i == 0) {
return false;
}
}
return true;
}
public static void main(String[] args) throws ParseException, NoSuchAlgorithmException {
int mb = 1024 * 1024;
int gb = 1024 * 1024 * 1024;
/* PHYSICAL MEMORY USAGE */
System.out.println("\n**** Sizes in Mega Bytes ****\n");
com.sun.management.OperatingSystemMXBean operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
//RuntimeMXBean runtimeMXBean = ManagementFactory.getRuntimeMXBean();
//operatingSystemMXBean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean) java.lang.management.ManagementFactory.getOperatingSystemMXBean();
for (int i = 0; i < 30; i++) {
long start = System.nanoTime();
// log(start);
//number of available processors;
int cpuCount = ManagementFactory.getOperatingSystemMXBean().getAvailableProcessors();
Random random = new Random(start);
int seed = Math.abs(random.nextInt());
log("\n \n CPU USAGE DETAILS \n\n");
log("Starting Test with " + cpuCount + " CPUs and random number:" + seed);
int primes = 10000;
//
long startCPUTime = ManagementFactory.getThreadMXBean().getCurrentThreadCpuTime();
start = System.nanoTime();
while (primes != 0) {
if (isPrime(seed)) {
primes--;
}
seed++;
}
float cpuPercent = calcCPU(startCPUTime, start, cpuCount);
log("CPU USAGE : " + cpuPercent + " % ");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
try {
Thread.sleep(500);
} catch (Exception ignored) {
}
}
I tried this but I think I can't check with this method usage cpu by one application
Upvotes: 2
Views: 226
Reputation: 1722
I think you can't do this at the moment out of the Java toolbox without calling native methods and/or third party libraries and/or calling platform specific command line commands.
The Java Process object is very limited at the moment.
The good news is that a new Process facility is coming in Java 9:
Summary
Improve the API for controlling and managing operating-system processes.
Motivation
The limitations of the current API often force developers to resort to native code.
Description
Java SE provides limited support for native operating-system processes. It provides a basic API to setup the environment and start a process. The process streams can, since Java SE 7, be redirected to files, pipes, or can be inherited. Once started, the API can be used to destroy the process and/or wait for the process to terminate.
Many enterprise applications and containers involve several Java virtual machines and processes and have long-standing needs which include:
The ability to get the pid (or equivalent) of the current Java virtual machine and the pid of processes created with the existing API.
The ability to enumerate processes on the system. Information on each process may include its pid, name, state, and perhaps resource usage.
The ability to deal with process trees, in particular some means to destroy a process tree.
The ability to deal with hundreds of sub-processes, perhaps multiplexing the output or error streams to avoid creating a thread per sub-process.
Edit: suggestion to use in case you want to user third party library.
You might want to take a look at Sigar:
Overview The Sigar API provides a portable interface for gathering system information such as:
System memory, swap, cpu, load average, uptime, logins Per-process memory, cpu, credential info, state, arguments, environment, open files File system detection and metrics Network interface detection, configuration info and metrics TCP and UDP connection tables Network route table This information is available in most operating systems, but each OS has their own way(s) providing it. SIGAR provides developers with one API to access this information regardless of the underlying platform. The core API is implemented in pure C with bindings currently implemented for Java, Perl, Ruby, Python, Erlang, PHP and C#.
Upvotes: 2