@Test void cpuUsageIsSetForMinAndMaxOnTheFirstRun() { when(this.osBean.retrieveCpuUsage()).thenReturn(10f); this.cut.gather(); CpuInformationData collector = (CpuInformationData) this.cut.get(); assertThat(collector.getMinCpuUsage(), is(10f)); assertThat(collector.getMaxCpuUsage(), is(10f)); assertThat(collector.getTotalCpuUsage(), is(10f)); }
@Test public void calculateCpuUsage() { int availableProc = 1; // process cpu time is provided as nanoseconds long processCpuTime1 = 200L * 1000 * 1000; // ns representation of 200ms long processCpuTime2 = 500L * 1000 * 1000; // ns representation of 500ms // uptime is provided in milliseconds long uptime1 = 500L; // 500ms long uptime2 = 1100L; // 1100ms when(runtimeBean.getUptime()).thenReturn(uptime1).thenReturn(uptime2); when(osBean.getAvailableProcessors()).thenReturn(availableProc); when(osBean.getProcessCpuTime()).thenReturn(processCpuTime1).thenReturn(processCpuTime2); float cpuUsage1 = wrapper.retrieveCpuUsage(); assertThat((double) cpuUsage1, is(closeTo(0.0d, 0.01d))); float cpuUsage2 = wrapper.retrieveCpuUsage(); // CPU usage can only be deduced after the second call long process = (processCpuTime2 - processCpuTime1); long upAsNano = ((uptime2 - uptime1) * 1000 * 1000); float expectedUsage = ((float) process / upAsNano) * 100; assertThat((double) cpuUsage2, is(closeTo(expectedUsage, 0.01d))); }
@Test void cpuUsageIsCalculated() { when(this.osBean.retrieveCpuUsage()).thenReturn(10f).thenReturn(9f).thenReturn(11f).thenReturn(10f); this.cut.gather(); this.cut.gather(); this.cut.gather(); this.cut.gather(); CpuInformationData collector = (CpuInformationData) this.cut.get(); assertThat(collector.getMinCpuUsage(), is(9f)); assertThat(collector.getMaxCpuUsage(), is(11f)); assertThat(collector.getTotalCpuUsage(), is(40f)); }
/** * {@inheritDoc} */ @Override public void gather() { // The timestamp is set in the {@link CpuInformation#reset()} to avoid multiple renewal. It // will not be set on the first execution of {@link CpuInformation#gather()}, but shortly // before. float cpuUsage = this.getOsBean().retrieveCpuUsage(); long cpuTime = this.getOsBean().getProcessCpuTime(); this.cpuInformationData.incrementCount(); this.cpuInformationData.updateProcessCpuTime(cpuTime); this.cpuInformationData.addCpuUsage(cpuUsage); if (cpuUsage < this.cpuInformationData.getMinCpuUsage()) { this.cpuInformationData.setMinCpuUsage(cpuUsage); } if (cpuUsage > this.cpuInformationData.getMaxCpuUsage()) { this.cpuInformationData.setMaxCpuUsage(cpuUsage); } }