1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88
|
public class CpuTime
{
private long nanoStart;
private ThreadMXBean thd;
private long previousTime;
private long currentTime;
public CpuTime()
{
nanoStart = 0L;
thd = ManagementFactory.getThreadMXBean();
previousTime = 0L;
currentTime = 0L;
}
/**
starts the chronometer
*/
public void start()
{
nanoStart = thd.getCurrentThreadUserTime();
}
/**
stops the chronometer
*/
public void stop()
{
long nanoStop = thd.getCurrentThreadUserTime();
previousTime = currentTime;
currentTime = nanoStop - nanoStart;
}
/**
Returns the CPU time beetween the last call of start and stop in seconds
*/
public double getSeconds()
{
return (currentTime)/1E9;
}
/**
Returns the CPU time beetween the last call of start and stop in milliseconds
*/
public long getMilliSeconds()
{
return (long) Math.round((currentTime)/1E6);
}
/**
Returns the CPU time beetween the last call of start and stop in nanoseconds
*/
public long getNanoSeconds()
{
return currentTime;
}
/**
Returns the CPU time beetween the last call of start and stop under string format (hh:mm:ss)
*/
public String getTime()
{
long rest = getMilliSeconds();
long ms = rest % 1000;
rest = rest / 1000; // expressed in sec
String time = ms + " ms";
String[] unit = {"sec","min","hours"};
long[] val = {60,60,24};
for (int i = 0; i < unit.length && rest > 0; i++)
{
long t = rest % val[i];
rest = rest / val[i];
time = t + " " + unit[i] + " " + time;
}
if (rest > 0)
time = rest + " days " + time;
return time;
}
} |