oshi.util.FormatUtil Java Examples

The following examples show how to use oshi.util.FormatUtil. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: RetrieveSystemDigest.java    From support-diagnostics with Apache License 2.0 7 votes vote down vote up
private static void printNetworkInterfaces(BufferedWriter writer, NetworkIF[] networkIFs) throws Exception {
    writer.write("Network interfaces");
    writer.newLine();
    writer.write("----------------");
    writer.newLine();

    for (NetworkIF net : networkIFs) {
        writer.write(String.format(" Name: %s (%s)%n", net.getName(), net.getDisplayName()));
        writer.write(String.format("   MAC Address: %s %n", net.getMacaddr()));
        writer.write(String.format("   MTU: %s, Speed: %s %n", net.getMTU(), FormatUtil.formatValue(net.getSpeed(), "bps")));
        writer.write(String.format("   IPv4: %s %n", Arrays.toString(net.getIPv4addr())));
        writer.write(String.format("   IPv6: %s %n", Arrays.toString(net.getIPv6addr())));
        boolean hasData = net.getBytesRecv() > 0 || net.getBytesSent() > 0 || net.getPacketsRecv() > 0
                || net.getPacketsSent() > 0;
        writer.write(String.format("   Traffic: received %s/%s%s; transmitted %s/%s%s %n",
                hasData ? net.getPacketsRecv() + " packets" : "?",
                hasData ? FormatUtil.formatBytes(net.getBytesRecv()) : "?",
                hasData ? " (" + net.getInErrors() + " err)" : "",
                hasData ? net.getPacketsSent() + " packets" : "?",
                hasData ? FormatUtil.formatBytes(net.getBytesSent()) : "?",
                hasData ? " (" + net.getOutErrors() + " err)" : ""));

    }
}
 
Example #2
Source File: SystemInfoTest.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
private static void printFileSystem(FileSystem fileSystem) {
    oshi.add("File System:");

    oshi.add(String.format(" File Descriptors: %d/%d", fileSystem.getOpenFileDescriptors(),
        fileSystem.getMaxFileDescriptors()));

    OSFileStore[] fsArray = fileSystem.getFileStores();
    for (OSFileStore fs : fsArray) {
        long usable = fs.getUsableSpace();
        long total = fs.getTotalSpace();
        oshi.add(String.format(
            " %s (%s) [%s] %s of %s free (%.1f%%), %s of %s files free (%.1f%%) is %s "
                + (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s")
                + " and is mounted at %s",
            fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(),
            FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total,
            FormatUtil.formatValue(fs.getFreeInodes(), ""), FormatUtil.formatValue(fs.getTotalInodes(), ""),
            100d * fs.getFreeInodes() / fs.getTotalInodes(), fs.getVolume(), fs.getLogicalVolume(),
            fs.getMount()));
    }
}
 
Example #3
Source File: RetrieveSystemDigest.java    From support-diagnostics with Apache License 2.0 6 votes vote down vote up
private static void printFileSystem(BufferedWriter writer, FileSystem fileSystem) throws Exception {
    writer.write("File System");
    writer.newLine();
    writer.write("-------------");
    writer.newLine();
    writer.write(String.format(" File Descriptors: %d/%d%n", fileSystem.getOpenFileDescriptors(),
            fileSystem.getMaxFileDescriptors()));

    OSFileStore[] fsArray = fileSystem.getFileStores();
    for (OSFileStore fs : fsArray) {
        long usable = fs.getUsableSpace();
        long total = fs.getTotalSpace();
        writer.write(String.format(" %s (%s) [%s] %s of %s free (%.1f%%) is %s and is mounted at %s%n", fs.getName(),
                fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(),
                FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total,
                fs.getVolume(), fs.getMount()));
    }
}
 
Example #4
Source File: RetrieveSystemDigest.java    From support-diagnostics with Apache License 2.0 6 votes vote down vote up
private static void printDisks(BufferedWriter writer, HWDiskStore[] diskStores) throws Exception {
    writer.write("Disks");
    writer.newLine();
    writer.write("-----");
    writer.newLine();

    for (HWDiskStore disk : diskStores) {
        boolean readwrite = disk.getReads() > 0 || disk.getWrites() > 0;
        writer.write(String.format(" %s: (model: %s - S/N: %s) size: %s, reads: %s (%s), writes: %s (%s), xfer: %s ms%n",
                disk.getName(), disk.getModel(), disk.getSerial(),
                disk.getSize() > 0 ? FormatUtil.formatBytesDecimal(disk.getSize()) : "?",
                readwrite ? disk.getReads() : "?", readwrite ? FormatUtil.formatBytes(disk.getReadBytes()) : "?",
                readwrite ? disk.getWrites() : "?", readwrite ? FormatUtil.formatBytes(disk.getWriteBytes()) : "?",
                readwrite ? disk.getTransferTime() : "?"));
        HWPartition[] partitions = disk.getPartitions();
        if (partitions == null) {
            continue;
        }
        for (HWPartition part : partitions) {
            writer.write(String.format(" |-- %s: %s (%s) Maj:Min=%d:%d, size: %s%s%n", part.getIdentification(),
                    part.getName(), part.getType(), part.getMajor(), part.getMinor(),
                    FormatUtil.formatBytesDecimal(part.getSize()),
                    part.getMountPoint().isEmpty() ? "" : " @ " + part.getMountPoint()));
        }
    }
}
 
Example #5
Source File: RetrieveSystemDigest.java    From support-diagnostics with Apache License 2.0 6 votes vote down vote up
private static void printProcesses(BufferedWriter writer, OperatingSystem os, GlobalMemory memory) throws Exception {
    writer.write("Processes");
    writer.newLine();
    writer.write("----------");
    writer.newLine();
    writer.write("Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount());
    writer.newLine();

    // Sort by highest CPU
    List<OSProcess> procs = Arrays.asList(os.getProcesses(os.getProcessCount(), ProcessSort.CPU));
    int sz = procs.size();
    writer.write("PID     %CPU  %MEM  VSZ      RSS      Name");
    for (int i = 0; i < sz; i++) {
        OSProcess p = procs.get(i);
        writer.write(String.format(" %5d %5.1f %4.1f %9s %9s %s%n", p.getProcessID(),
                100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(),
                100d * p.getResidentSetSize() / memory.getTotal(), FormatUtil.formatBytes(p.getVirtualSize()),
                FormatUtil.formatBytes(p.getResidentSetSize()), p.getName()));
    }
}
 
Example #6
Source File: OshiPlatformCacheTest.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
@Test
public void getMemory() {
    OshiPlatformCache oshi = newOshiPlatformCache();
    GlobalMemory memory = oshi.getMemory();
    Assert.assertNotNull(memory);

    long avail = memory.getAvailable();
    long total = memory.getTotal();

    Assert.assertTrue(avail > -1L);
    Assert.assertTrue(total > -1L);

    print("===MEMORY ===");
    print("  Available=[%s] (%d)", FormatUtil.formatBytes(avail), avail);
    print("  Total=[%s] (%d)", FormatUtil.formatBytes(total), total);
    print("  toString=[%s]", memory.toString());
}
 
Example #7
Source File: OshiPlatformCacheTest.java    From hawkular-agent with Apache License 2.0 6 votes vote down vote up
@Test
public void getFileStores() {
    OshiPlatformCache oshi = newOshiPlatformCache();
    Map<String, OSFileStore> filestores = oshi.getFileStores();
    Assert.assertNotNull(filestores);

    int i = 0;
    for (OSFileStore filestore : filestores.values()) {
        String name = filestore.getName();
        String description = filestore.getDescription();
        long usableSpace = filestore.getUsableSpace();
        long totalSpace = filestore.getTotalSpace();

        Assert.assertNotNull(name);
        Assert.assertNotNull(description);
        Assert.assertTrue(usableSpace > -1L);
        Assert.assertTrue(totalSpace > -1L);

        print("===FILE STORE #%d ===", ++i);
        print("  Name=[%s]", name);
        print("  Description=[%s]", description);
        print("  UsableSpace=[%s] (%d)", FormatUtil.formatBytes(usableSpace), usableSpace);
        print("  TotalSpace=[%s] (%d)", FormatUtil.formatBytes(totalSpace), totalSpace);
        print("  toString=[%s]", filestore.toString());
    }
}
 
Example #8
Source File: SystemInfoUtil.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static void printFileSystem(FileSystem fileSystem) {
    System.out.println("File System:");
    System.out.format(" File Descriptors: %d/%d%n", fileSystem.getOpenFileDescriptors(),
        fileSystem.getMaxFileDescriptors());
    OSFileStore[] fsArray = fileSystem.getFileStores();
    for (OSFileStore fs : fsArray) {
        long usable = fs.getUsableSpace();
        long total = fs.getTotalSpace();
        System.out.format(
            " %s (%s) [%s] %s of %s free (%.1f%%) is %s "
                + (fs.getLogicalVolume() != null && fs.getLogicalVolume().length() > 0 ? "[%s]" : "%s")
                + " and is mounted at %s%n",
            fs.getName(), fs.getDescription().isEmpty() ? "file system" : fs.getDescription(), fs.getType(),
            FormatUtil.formatBytes(usable), FormatUtil.formatBytes(fs.getTotalSpace()), 100d * usable / total,
            fs.getVolume(), fs.getLogicalVolume(), fs.getMount());
    }
}
 
Example #9
Source File: SystemInfoUtil.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static void printNetworkInterfaces(NetworkIF[] networkIFs) {
    System.out.println("Network interfaces:");
    for (NetworkIF net : networkIFs) {
        System.out.format(" Name: %s (%s)%n", net.getName(), net.getDisplayName());
        System.out.format("   MAC Address: %s %n", net.getMacaddr());
        System.out.format("   MTU: %s, Speed: %s %n", net.getMTU(), FormatUtil.formatValue(net.getSpeed(), "bps"));
        System.out.format("   IPv4: %s %n", Arrays.toString(net.getIPv4addr()));
        System.out.format("   IPv6: %s %n", Arrays.toString(net.getIPv6addr()));
        boolean hasData = net.getBytesRecv() > 0 || net.getBytesSent() > 0 || net.getPacketsRecv() > 0
            || net.getPacketsSent() > 0;
        System.out.format("   Traffic: received %s/%s%s; transmitted %s/%s%s %n",
            hasData ? net.getPacketsRecv() + " packets" : "?",
            hasData ? FormatUtil.formatBytes(net.getBytesRecv()) : "?",
            hasData ? " (" + net.getInErrors() + " err)" : "",
            hasData ? net.getPacketsSent() + " packets" : "?",
            hasData ? FormatUtil.formatBytes(net.getBytesSent()) : "?",
            hasData ? " (" + net.getOutErrors() + " err)" : "");
    }
}
 
Example #10
Source File: SystemInfoUtil.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 6 votes vote down vote up
public static void printDisks(HWDiskStore[] diskStores) {
    System.out.println("Disks:");
    for (HWDiskStore disk : diskStores) {
        boolean readwrite = disk.getReads() > 0 || disk.getWrites() > 0;
        System.out.format(" %s: (model: %s - S/N: %s) size: %s, reads: %s (%s), writes: %s (%s), xfer: %s ms%n",
            disk.getName(), disk.getModel(), disk.getSerial(),
            disk.getSize() > 0 ? FormatUtil.formatBytesDecimal(disk.getSize()) : "?",
            readwrite ? disk.getReads() : "?", readwrite ? FormatUtil.formatBytes(disk.getReadBytes()) : "?",
            readwrite ? disk.getWrites() : "?", readwrite ? FormatUtil.formatBytes(disk.getWriteBytes()) : "?",
            readwrite ? disk.getTransferTime() : "?");
        HWPartition[] partitions = disk.getPartitions();
        if (partitions == null) {
            // TODO Remove when all OS's implemented
            continue;
        }
        for (HWPartition part : partitions) {
            System.out.format(" |-- %s: %s (%s) Maj:Min=%d:%d, size: %s%s%n", part.getIdentification(),
                part.getName(), part.getType(), part.getMajor(), part.getMinor(),
                FormatUtil.formatBytesDecimal(part.getSize()),
                part.getMountPoint().isEmpty() ? "" : " @ " + part.getMountPoint());
        }
    }
}
 
Example #11
Source File: SystemInfoUtil.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
public static void printProcesses(OperatingSystem os, GlobalMemory memory) {
    System.out.println("Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount());
    // Sort by highest CPU
    List<OSProcess> procs = Arrays.asList(os.getProcesses(5, OperatingSystem.ProcessSort.CPU));
    System.out.println("   PID  %CPU %MEM       VSZ       RSS Name");
    for (int i = 0; i < procs.size() && i < 5; i++) {
        OSProcess p = procs.get(i);
        System.out.format(" %5d %5.1f %4.1f %9s %9s %s%n", p.getProcessID(),
            100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(),
            100d * p.getResidentSetSize() / memory.getTotal(), FormatUtil.formatBytes(p.getVirtualSize()),
            FormatUtil.formatBytes(p.getResidentSetSize()), p.getName());
    }
}
 
Example #12
Source File: SystemInfoTest.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 5 votes vote down vote up
private static void printProcesses(OperatingSystem os, GlobalMemory memory) {
    oshi.add("Processes: " + os.getProcessCount() + ", Threads: " + os.getThreadCount());
    // Sort by highest CPU
    List<OSProcess> procs = Arrays.asList(os.getProcesses(5, ProcessSort.CPU));

    oshi.add("   PID  %CPU %MEM       VSZ       RSS Name");
    for (int i = 0; i < procs.size() && i < 5; i++) {
        OSProcess p = procs.get(i);
        oshi.add(String.format(" %5d %5.1f %4.1f %9s %9s %s", p.getProcessID(),
            100d * (p.getKernelTime() + p.getUserTime()) / p.getUpTime(),
            100d * p.getResidentSetSize() / memory.getTotal(), FormatUtil.formatBytes(p.getVirtualSize()),
            FormatUtil.formatBytes(p.getResidentSetSize()), p.getName()));
    }
}
 
Example #13
Source File: MonitorServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
/**
 * 获取交换区信息
 * @param memory /
 * @return /
 */
private Map<String,Object> getSwapInfo(GlobalMemory memory) {
    Map<String,Object> swapInfo = new LinkedHashMap<>();
    swapInfo.put("total", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapTotal()));
    swapInfo.put("used", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapUsed()));
    swapInfo.put("available", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapTotal() - memory.getVirtualMemory().getSwapUsed()));
    swapInfo.put("usageRate", df.format(memory.getVirtualMemory().getSwapUsed()/(double)memory.getVirtualMemory().getSwapTotal() * 100));
    return swapInfo;
}
 
Example #14
Source File: MonitorServiceImpl.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取交换区信息
 *
 * @param memory /
 * @return /
 */
private Map<String, Object> getSwapInfo(GlobalMemory memory) {
	Map<String, Object> swapInfo = new LinkedHashMap<>();
	swapInfo.put("total", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapTotal()));
	swapInfo.put("used", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapUsed()));
	swapInfo.put("available", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapTotal() - memory.getVirtualMemory().getSwapUsed()));
	swapInfo.put("usageRate", df.format(memory.getVirtualMemory().getSwapTotal() <= 0 ? 0 : memory.getVirtualMemory().getSwapUsed() / (double) memory.getVirtualMemory().getSwapTotal() * 100));
	return swapInfo;
}
 
Example #15
Source File: MonitorServiceImpl.java    From albedo with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * 获取内存信息
 *
 * @param memory /
 * @return /
 */
private Map<String, Object> getMemoryInfo(GlobalMemory memory) {
	Map<String, Object> memoryInfo = new LinkedHashMap<>();
	memoryInfo.put("total", FormatUtil.formatBytes(memory.getTotal()));
	memoryInfo.put("available", FormatUtil.formatBytes(memory.getAvailable()));
	memoryInfo.put("used", FormatUtil.formatBytes(memory.getTotal() - memory.getAvailable()));
	memoryInfo.put("usageRate", df.format((memory.getTotal() - memory.getAvailable()) / (double) memory.getTotal() * 100));
	return memoryInfo;
}
 
Example #16
Source File: OshiPlatformCacheTest.java    From hawkular-agent with Apache License 2.0 5 votes vote down vote up
@Test
public void getPowerSources() {
    OshiPlatformCache oshi = newOshiPlatformCache();
    Map<String, PowerSource> powersources = oshi.getPowerSources();
    Assert.assertNotNull(powersources);

    if (powersources.size() == 0) {
        print("===NO POWER SOURCES ON THIS MACHINE===");
    } else {
        int i = 0;
        for (PowerSource powersource : powersources.values()) {
            String name = powersource.getName();
            double remainingCapacity = powersource.getRemainingCapacity();
            double timeRemaining = powersource.getTimeRemaining();

            Assert.assertNotNull(name);

            print("===POWER SOURCE #%d ===", ++i);
            print("  Name=[%s]", name);
            print("  RemainingCapacity=[%.0f%%] (%.2f)", remainingCapacity * 100, remainingCapacity);
            long roundedTimeRemaining = Math.round(timeRemaining);
            if (roundedTimeRemaining == -1) {
                print("  TimeRemaining=[calculating] (%.1f)", timeRemaining);
            } else if (roundedTimeRemaining == -2) {
                print("  TimeRemaining=[unlimited] (%.1f)", timeRemaining);
            } else {
                print("  TimeRemaining=[%s] (%.1f)", FormatUtil.formatElapsedSecs(roundedTimeRemaining),
                        timeRemaining);
            }
            print("  toString=[%s]", powersource.toString());
        }
    }
}
 
Example #17
Source File: RetrieveSystemDigest.java    From support-diagnostics with Apache License 2.0 5 votes vote down vote up
private static void printMemory(BufferedWriter writer, GlobalMemory memory) throws Exception {
    writer.write("Memory");
    writer.newLine();
    writer.write("-------");
    writer.newLine();

    writer.write("Memory: " + FormatUtil.formatBytes(memory.getAvailable()) + "/"
            + FormatUtil.formatBytes(memory.getTotal()));
    writer.newLine();

    writer.write("Swap used: " + FormatUtil.formatBytes(memory.getSwapUsed()) + "/"
            + FormatUtil.formatBytes(memory.getSwapTotal()));
    writer.newLine();

}
 
Example #18
Source File: ServerServiceImpl.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
/**
 * 获取内存信息
 *
 * @param memory /
 * @return /
 */
private Map<String, Object> getMemoryInfo(GlobalMemory memory) {
    Map<String, Object> memoryInfo = new LinkedHashMap<>();
    memoryInfo.put("total", FormatUtil.formatBytes(memory.getTotal()));
    memoryInfo.put("available", FormatUtil.formatBytes(memory.getAvailable()));
    memoryInfo.put("used", FormatUtil.formatBytes(memory.getTotal() - memory.getAvailable()));
    memoryInfo.put("usageRate", df.format((memory.getTotal() - memory.getAvailable()) / (double) memory.getTotal() * 100));
    return memoryInfo;
}
 
Example #19
Source File: ServerServiceImpl.java    From DimpleBlog with Apache License 2.0 5 votes vote down vote up
/**
 * 获取交换区信息
 *
 * @param memory /
 * @return /
 */
private Map<String, Object> getSwapInfo(GlobalMemory memory) {
    Map<String, Object> swapInfo = new LinkedHashMap<>();
    swapInfo.put("total", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapTotal()));
    swapInfo.put("used", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapUsed()));
    swapInfo.put("available", FormatUtil.formatBytes(memory.getVirtualMemory().getSwapTotal() - memory.getVirtualMemory().getSwapUsed()));
    swapInfo.put("usageRate", df.format(memory.getVirtualMemory().getSwapUsed() / (double) memory.getVirtualMemory().getSwapTotal() * 100));
    return swapInfo;
}
 
Example #20
Source File: MonitorServiceImpl.java    From eladmin with Apache License 2.0 5 votes vote down vote up
/**
 * 获取内存信息
 * @param memory /
 * @return /
 */
private Map<String,Object> getMemoryInfo(GlobalMemory memory) {
    Map<String,Object> memoryInfo = new LinkedHashMap<>();
    memoryInfo.put("total", FormatUtil.formatBytes(memory.getTotal()));
    memoryInfo.put("available", FormatUtil.formatBytes(memory.getAvailable()));
    memoryInfo.put("used", FormatUtil.formatBytes(memory.getTotal() - memory.getAvailable()));
    memoryInfo.put("usageRate", df.format((memory.getTotal() - memory.getAvailable())/(double)memory.getTotal() * 100));
    return memoryInfo;
}
 
Example #21
Source File: SystemInfoTest.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
private static void printOperatingSystem(final OperatingSystem os) {
    oshi.add(String.valueOf(os));
    oshi.add("Booted: " + Instant.ofEpochSecond(os.getSystemBootTime()));
    oshi.add("Uptime: " + FormatUtil.formatElapsedSecs(os.getSystemUptime()));
    oshi.add("Running with" + (os.isElevated() ? "" : "out") + " elevated permissions.");
}
 
Example #22
Source File: SystemInfoTest.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
private static void printCpu(CentralProcessor processor) {
    oshi.add("Context Switches/Interrupts: " + processor.getContextSwitches() + " / " + processor.getInterrupts());

    long[] prevTicks = processor.getSystemCpuLoadTicks();
    long[][] prevProcTicks = processor.getProcessorCpuLoadTicks();
    oshi.add("CPU, IOWait, and IRQ ticks @ 0 sec:" + Arrays.toString(prevTicks));
    // Wait a second...
    Util.sleep(1000);
    long[] ticks = processor.getSystemCpuLoadTicks();
    oshi.add("CPU, IOWait, and IRQ ticks @ 1 sec:" + Arrays.toString(ticks));
    long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
    long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
    long sys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
    long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
    long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
    long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
    long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
    long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
    long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;

    oshi.add(String.format(
        "User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%",
        100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu,
        100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu));
    oshi.add(String.format("CPU load: %.1f%%", processor.getSystemCpuLoadBetweenTicks(prevTicks) * 100));
    double[] loadAverage = processor.getSystemLoadAverage(3);
    oshi.add("CPU load averages:" + (loadAverage[0] < 0 ? " N/A" : String.format(" %.2f", loadAverage[0]))
        + (loadAverage[1] < 0 ? " N/A" : String.format(" %.2f", loadAverage[1]))
        + (loadAverage[2] < 0 ? " N/A" : String.format(" %.2f", loadAverage[2])));
    // per core CPU
    StringBuilder procCpu = new StringBuilder("CPU load per processor:");
    double[] load = processor.getProcessorCpuLoadBetweenTicks(prevProcTicks);
    for (double avg : load) {
        procCpu.append(String.format(" %.1f%%", avg * 100));
    }
    oshi.add(procCpu.toString());
    long freq = processor.getProcessorIdentifier().getVendorFreq();
    if (freq > 0) {
        oshi.add("Vendor Frequency: " + FormatUtil.formatHertz(freq));
    }
    freq = processor.getMaxFreq();
    if (freq > 0) {
        oshi.add("Max Frequency: " + FormatUtil.formatHertz(freq));
    }
    long[] freqs = processor.getCurrentFreq();
    if (freqs[0] > 0) {
        StringBuilder sb = new StringBuilder("Current Frequencies: ");
        for (int i = 0; i < freqs.length; i++) {
            if (i > 0) {
                sb.append(", ");
            }
            sb.append(FormatUtil.formatHertz(freqs[i]));
        }
        oshi.add(sb.toString());
    }
}
 
Example #23
Source File: SystemInfoUtil.java    From javatech with Creative Commons Attribution Share Alike 4.0 International 4 votes vote down vote up
public static void printMemory(GlobalMemory memory) {
    System.out.println("以使用内存: " + FormatUtil.formatBytes(memory.getAvailable()) + "总共内存"
        + FormatUtil.formatBytes(memory.getTotal()));
}
 
Example #24
Source File: RetrieveSystemDigest.java    From support-diagnostics with Apache License 2.0 4 votes vote down vote up
private static void printCpu(BufferedWriter writer, CentralProcessor processor) throws Exception {
    writer.write("CPU");
    writer.newLine();
    writer.write("---");
    writer.newLine();
    writer.write("Uptime: " + FormatUtil.formatElapsedSecs(processor.getSystemUptime()));
    writer.newLine();

    writer.write(
            "Context Switches/Interrupts: " + processor.getContextSwitches() + " / " + processor.getInterrupts());
    writer.newLine();


    long[] prevTicks = processor.getSystemCpuLoadTicks();

    writer.write("CPU, IOWait, and IRQ ticks @ 0 sec:" + Arrays.toString(prevTicks));
    writer.newLine();

    // Wait a second...
    Util.sleep(1000);
    long[] ticks = processor.getSystemCpuLoadTicks();

    writer.write("CPU, IOWait, and IRQ ticks @ 1 sec:" + Arrays.toString(ticks));
    writer.newLine();

    long user = ticks[TickType.USER.getIndex()] - prevTicks[TickType.USER.getIndex()];
    long nice = ticks[TickType.NICE.getIndex()] - prevTicks[TickType.NICE.getIndex()];
    long sys = ticks[TickType.SYSTEM.getIndex()] - prevTicks[TickType.SYSTEM.getIndex()];
    long idle = ticks[TickType.IDLE.getIndex()] - prevTicks[TickType.IDLE.getIndex()];
    long iowait = ticks[TickType.IOWAIT.getIndex()] - prevTicks[TickType.IOWAIT.getIndex()];
    long irq = ticks[TickType.IRQ.getIndex()] - prevTicks[TickType.IRQ.getIndex()];
    long softirq = ticks[TickType.SOFTIRQ.getIndex()] - prevTicks[TickType.SOFTIRQ.getIndex()];
    long steal = ticks[TickType.STEAL.getIndex()] - prevTicks[TickType.STEAL.getIndex()];
    long totalCpu = user + nice + sys + idle + iowait + irq + softirq + steal;

    writer.write(String.format(
            "User: %.1f%% Nice: %.1f%% System: %.1f%% Idle: %.1f%% IOwait: %.1f%% IRQ: %.1f%% SoftIRQ: %.1f%% Steal: %.1f%%%n",
            100d * user / totalCpu, 100d * nice / totalCpu, 100d * sys / totalCpu, 100d * idle / totalCpu,
            100d * iowait / totalCpu, 100d * irq / totalCpu, 100d * softirq / totalCpu, 100d * steal / totalCpu));
    writer.newLine();

    writer.write(String.format("CPU load: %.1f%% (counting ticks)%n", processor.getSystemCpuLoadBetweenTicks() * 100));
    writer.write(String.format("CPU load: %.1f%% (OS MXBean)%n", processor.getSystemCpuLoad() * 100));
    double[] loadAverage = processor.getSystemLoadAverage(3);
    writer.write("CPU load averages:" + (loadAverage[0] < 0 ? " N/A" : String.format(" %.2f", loadAverage[0]))
            + (loadAverage[1] < 0 ? " N/A" : String.format(" %.2f", loadAverage[1]))
            + (loadAverage[2] < 0 ? " N/A" : String.format(" %.2f", loadAverage[2])));
    // per core CPU
    StringBuilder procCpu = new StringBuilder("CPU load per processor:");
    double[] load = processor.getProcessorCpuLoadBetweenTicks();
    for (double avg : load) {
        procCpu.append(String.format(" %.1f%%", avg * 100));
    }
    writer.write(procCpu.toString());
    writer.newLine();

}