package test;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
public class CpuRateByCore {
public static int INTERVAL = 1000;
public static String[] getCpuUsageByCore() {
String[] result = null;
String[] command = { "bash", "-c", "cat /proc/stat | grep 'cpu[0-9]'" };
Runtime runtime = Runtime.getRuntime();
BufferedReader reader = null;
List<CpuInfoVo> prevInfoList = new ArrayList<CpuInfoVo>();
List<CpuInfoVo> diffInfoList = new ArrayList<CpuInfoVo>();
try {
Process process = runtime.exec(command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
String line = null;
String[] columns = null;
long total = 0;
long idle = 0;
int x = 0;
while ( (line = reader.readLine()) != null ) {
// System.out.println(line);
line = line.replace(" ", " ");
columns = line.split(" ");
total = 0;
idle = 0;
for ( int i = 1 ; i < columns.length ; i++ ) {
total += Long.parseLong(columns[i]);
}
idle = Long.parseLong(columns[4]);
CpuInfoVo vo = new CpuInfoVo();
vo.setTotal(total);
vo.setIdle(idle);
prevInfoList.add(vo);
x++;
}
// sleep 1sec
//Thread.sleep(INTERVAL);
process = runtime.exec(command);
reader = new BufferedReader(new InputStreamReader(process.getInputStream()));
x = 0;
while ( (line = reader.readLine()) != null ) {
line = line.replace(" ", " ");
columns = line.split(" ");
total = 0;
idle = 0;
for ( int i = 1 ; i < columns.length ; i++ ) {
total += Long.parseLong(columns[i]);
}
idle = Long.parseLong(columns[4]);
long diffTotal = total - prevInfoList.get(x).getTotal();
long diffIdle = idle - prevInfoList.get(x).getIdle();
long cpuRate = 0;
if (diffTotal != 0)
cpuRate = 100 * ( diffTotal - diffIdle ) / diffTotal;
CpuInfoVo vo = new CpuInfoVo();
vo.setTotal(diffTotal);
vo.setIdle(diffIdle);
vo.setRate(cpuRate);
diffInfoList.add(vo);
x++;
}
result = new String[diffInfoList.size()];
for (int i=0; i<diffInfoList.size(); i++) {
CpuInfoVo cpuInfoVo = (CpuInfoVo)diffInfoList.get(i);
result[i] = Long.toString(cpuInfoVo.getRate());
}
}
catch ( Exception e ) {
e.printStackTrace();
}
return result;
}
public static void main(String[] args) throws Exception {
String[] cpuRates = getCpuUsageByCore();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
String ymd = sdf.format(Calendar.getInstance().getTime().getTime());
StringBuilder message = new StringBuilder();
message.append(ymd);
int total = 0;
for ( int i = 0 ; i < cpuRates.length ; i++ ) {
message.append(" ").append(cpuRates[i]);
total += Integer.parseInt(cpuRates[i]);
}
int cpuRate = total / cpuRates.length;
message.append(" (avg)").append(cpuRate);
System.out.println(message);
}
}
댓글 없음:
댓글 쓰기