From 531c3e32c6bb45a42cebc3761fbda9d58f4dd9a5 Mon Sep 17 00:00:00 2001 From: Doug MacEachern Date: Wed, 9 Mar 2005 17:03:50 +0000 Subject: [PATCH] reusable cpu timer --- .../java/src/net/hyperic/sigar/CpuTimer.java | 109 ++++++++++++++++++ 1 file changed, 109 insertions(+) create mode 100644 bindings/java/src/net/hyperic/sigar/CpuTimer.java diff --git a/bindings/java/src/net/hyperic/sigar/CpuTimer.java b/bindings/java/src/net/hyperic/sigar/CpuTimer.java new file mode 100644 index 00000000..ef7e90bf --- /dev/null +++ b/bindings/java/src/net/hyperic/sigar/CpuTimer.java @@ -0,0 +1,109 @@ +package net.hyperic.sigar; + +import java.io.PrintStream; + +public class CpuTimer { + private Sigar sigar; + private long totalTime; + private long cpuTotal; + private long cpuUser; + private long cpuSys; + + private ThreadCpu cpu = new ThreadCpu(); + + private long startTime; + + public CpuTimer() { + this(new Sigar()); + } + + public CpuTimer(Sigar sigar) { + this.sigar = sigar; + } + + public void start() { + this.startTime = System.currentTimeMillis(); + this.totalTime = 0; + this.cpuTotal = 0; + this.cpuUser = 0; + this.cpuSys = 0; + + try { + this.cpu.gather(this.sigar, 0); + } catch (SigarException e) { + throw new IllegalArgumentException(e.toString()); + } + } + + public void stop() { + ThreadCpu diff = getDiff(); + + this.cpuTotal = diff.total; + this.cpuUser = diff.user; + this.cpuSys = diff.sys; + + long stopTime = System.currentTimeMillis(); + + long time = stopTime - this.startTime; + + this.totalTime = time; + } + + public ThreadCpu getDiff() { + long startTotal = this.cpu.total; + long startUser = this.cpu.user; + long startSys = this.cpu.sys; + + ThreadCpu diff = new ThreadCpu(); + + try { + this.cpu.gather(this.sigar, 0); + } catch (SigarException e) { + throw new IllegalArgumentException(e.toString()); + } + + diff.total = this.cpu.total - startTotal; + diff.user = this.cpu.user - startUser; + diff.sys = this.cpu.sys - startSys; + + return diff; + } + + public long getTotalTime() { + return this.totalTime; + } + + public long getCpuTotal() { + return this.cpuTotal / 1000000; //convert nanos to millis + } + + public long getCpuUser() { + return this.cpuUser / 1000000; //convert nanos to millis + } + + public long getCpuSys() { + return this.cpuSys / 1000000; //convert nanos to millis + } + + public String format(long elap) { + String fraction = (elap % 1000) + ""; + int pad = 3 - fraction.length(); + + StringBuffer buf = new StringBuffer() + .append(elap / 1000).append('.'); + + //for example, 15 millseconds formatted as ".015" rather than ".15" + while (pad-- > 0) { + buf.append("0"); + } + buf.append(fraction).append(" seconds"); + return buf.toString(); + } + + public void list(PrintStream out) { + out.println("real....." + + format(getTotalTime())); + out.println("user....." + format(getCpuUser())); + out.println("sys......" + format(getCpuSys())); + } +}