Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

The CPU usage of a process for a period of time #41

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
77 changes: 77 additions & 0 deletions src/main/java/com/jezhumble/javasysmon/JavaSysMon.java
Original file line number Diff line number Diff line change
Expand Up @@ -281,4 +281,81 @@ public boolean visit(OsProcess process, int level) {
public void infanticide() {
killProcessTree(currentPid(), true);
}


/**
* @param The CPU usage of a process for a period of time
* @return get the Process Usage in period time
*/
private float getProcessUsage(JavaSysMon monitor, String pid, String period) {

long cpuTotalTimeBegin = getCpuTotalTime(monitor);
long processTotalTimeBegin = getProcessTotalTimeByPid(monitor, Integer.parseInt(pid));

try {
Thread.sleep(Long.parseLong(period));
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

long cpuTotalTimeEnd = getCpuTotalTime(monitor);
long processTotalTimeEnd = getProcessTotalTimeByPid(monitor, Integer.parseInt(pid));

float processUsage = (float) (processTotalTimeEnd - processTotalTimeBegin)
/ (float) (cpuTotalTimeEnd - cpuTotalTimeBegin);

return processUsage;

}

/**
*
* @param the object of JavaSysMon
* @return Get time of the CPU has spent in user mode, kernel mode,
* and idle.
*
*/
public long getCpuTotalTime(JavaSysMon monitor) {

return monitor.cpuTimes().getTotalMillis();
}

/**
*
* @param the object of JavaSysMon and the process pid
* @return Get the pid of Process use the cpu total time.
*
*/
public long getProcessTotalTimeByPid(JavaSysMon monitor, int pid) {

ProcessInfo processInfo = findProcessByPid(monitor, pid);

if (processInfo == null) {
return 0;
}
return processInfo.getSystemMillis() + processInfo.getUserMillis();
}

/**
*
* @param the object of JavaSysMon and the Process pid
*
* @return Get the ProcessInfo.
*
*/
public ProcessInfo findProcessByPid(JavaSysMon monitor, int pid) {

ProcessInfo[] processInfos = monitor.processTable();

for (ProcessInfo processInfo : processInfos) {

if (pid == processInfo.getPid()) {
return processInfo;
}
}

return null;
}

}