org.openxma.dsl.common.logging.TimeMeasurement Maven / Gradle / Ivy
package org.openxma.dsl.common.logging;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class TimeMeasurement {
private String category;
private String name;
private long begin=-1;
private long end=-1;
TimeMeasurement parent;
private List childMeasurements = new ArrayList();
public TimeMeasurement(String name) {
this.name = name;
}
public TimeMeasurement(String category, String name) {
this.name = name;
this.category = category;
}
public void addChild(TimeMeasurement child) {
childMeasurements.add(child);
}
public void begin() {
if (TimeLogger.getRoot() != null) {
parent = TimeLogger.getActiveTimeMeasurement();
if (parent != null ) {
parent.addChild(this);
}
TimeLogger.setActiveTimeMeasurement(this);
begin = System.currentTimeMillis();
}
}
public void end() {
if (TimeLogger.getRoot() != null) {
end = System.currentTimeMillis();
TimeLogger.setActiveTimeMeasurement(this.parent);
TimeLogger.addTimeMeasurement(this);
}
}
public long getDuration() {
if (begin >=0 && end >=0 ) {
return end-begin;
}
return -1;
}
public long getChildDuration() {
long cd=0;
for (TimeMeasurement tm : childMeasurements) {
cd+=tm.getDuration();
}
return cd;
}
public String getName() {
if (category != null) {
return category +" "+name;
}
return name;
}
public void print(String prefix, int stackDepth) {
int length = prefix.length();
if (stackDepth == length) return;
if (length == 0) {
System.out.println("Duration in [ms]:");
System.out.println("---------------------------------------------------------------------------------");
System.out.println("Total\tSelf\tOther\t\tAction");
System.out.println("---------------------------------------------------------------------------------");
}
long childDuration = (stackDepth == length+1) ? 0 : getChildDuration();
if (category != null) {
Durations s = TimeLogger.getSums().get(category);
if (s == null) {
s = new Durations();
TimeLogger.getSums().put(category, s);
}
s.total+=getDuration();
s.child+=childDuration;
} else {
System.out.println(getDuration()+"\t"+(getDuration()-childDuration)+"\t"+childDuration+"\t"+prefix+"\t"+getName());
}
for (TimeMeasurement m : childMeasurements) {
m.print(prefix+".",stackDepth);
}
if (length == 0) {
System.out.println("---------------------------------------------------------------------------------");
Iterator it = TimeLogger.getSums().keySet().iterator();
while (it.hasNext()) {
String key = it.next();
Durations d = TimeLogger.getSums().get(key);
System.out.println(d.total+"\t"+(d.total-d.child)+"\t"+d.child+"\t"+"-"+"\t"+"Category sum: "+key);
}
System.out.println("---------------------------------------------------------------------------------");
}
}
}