MachineCpuStatistics extends AbstractStatistic { @VisibleForTesting static void collectCpuTicks(long[] ticks, long[] prevTicks, StatisticsSink sink) { long user = ticks[CentralProcessor.TickType.USER.getIndex()] - prevTicks[CentralProcessor.TickType.USER.getIndex()]; long nice = ticks[CentralProcessor.TickType.NICE.getIndex()] - prevTicks[CentralProcessor.TickType.NICE.getIndex()]; long sys = ticks[CentralProcessor.TickType.SYSTEM.getIndex()] - prevTicks[CentralProcessor.TickType.SYSTEM.getIndex()]; long idle = ticks[CentralProcessor.TickType.IDLE.getIndex()] - prevTicks[CentralProcessor.TickType.IDLE.getIndex()]; long iowait = ticks[CentralProcessor.TickType.IOWAIT.getIndex()] - prevTicks[CentralProcessor.TickType.IOWAIT.getIndex()]; long irq = ticks[CentralProcessor.TickType.IRQ.getIndex()] - prevTicks[CentralProcessor.TickType.IRQ.getIndex()]; long softirq = ticks[CentralProcessor.TickType.SOFTIRQ.getIndex()] - prevTicks[CentralProcessor.TickType.SOFTIRQ.getIndex()]; long totalCpu = user + nice + sys + idle + iowait + irq + softirq; if (totalCpu > 0) { sink.addPercentage(CPU_VAR_USER, roundPercentage(user, totalCpu)); sink.addPercentage(CPU_VAR_NICE, roundPercentage(nice, totalCpu)); sink.addPercentage(CPU_VAR_SYS, roundPercentage(sys, totalCpu)); sink.addPercentage(CPU_VAR_IDLE, roundPercentage(idle, totalCpu)); sink.addPercentage(CPU_VAR_IOWAIT, roundPercentage(iowait, totalCpu)); sink.addPercentage(CPU_VAR_IRQ, roundPercentage(irq, totalCpu)); sink.addPercentage(CPU_VAR_SOFTIRQ, roundPercentage(softirq, totalCpu)); } } MachineCpuStatistics();   }
@Test public void collectCpuTicks() { long[] prevTicks = new long[8]; long[] ticks = new long[] {12, 34, 56, 78, 90, 21, 43, 65, 0}; StatisticsLog sink = new StatisticsLog(); MachineCpuStatistics.collectCpuTicks(ticks, prevTicks, sink); Assert.assertEquals("%user=4.0, %nice=10.0, %sys=17.0, %idle=23.0, %iowait=27.0, %irq=6.0, %softirq=13.0", sink.toString()); }