Created
May 25, 2015 00:45
-
-
Save svzdvd/c3337832d39b77a0d986 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.LinkedList; | |
import java.util.concurrent.TimeUnit; | |
public class StopWatchTree | |
{ | |
private final String name; | |
private final long startNanoTime; | |
private final LinkedList<StopWatchTree> children; | |
private boolean isRunning; | |
private long elapsedNanos; | |
public StopWatchTree(String name) | |
{ | |
this.name = name; | |
this.startNanoTime = System.nanoTime(); | |
this.children = new LinkedList<>(); | |
this.isRunning = true; | |
} | |
private void checkIsRunning() | |
{ | |
if (!isRunning) | |
{ | |
throw new IllegalArgumentException("StopWatch is not running"); | |
} | |
} | |
public void start(String name) | |
{ | |
checkIsRunning(); | |
if (!children.isEmpty() && children.getLast().isRunning) | |
{ | |
children.getLast().start(name); | |
} | |
else | |
{ | |
children.add(new StopWatchTree(name)); | |
} | |
} | |
public void stop() | |
{ | |
checkIsRunning(); | |
if (!children.isEmpty() && children.getLast().isRunning) | |
{ | |
children.getLast().stop(); | |
} | |
else | |
{ | |
elapsedNanos = System.nanoTime() - startNanoTime; | |
isRunning = false; | |
} | |
} | |
public String toString() | |
{ | |
return toString(TimeUnit.MICROSECONDS); | |
} | |
public String toString(TimeUnit timeUnit) | |
{ | |
StringBuilder builder = new StringBuilder(); | |
toString(builder, timeUnit, 0, ""); | |
return builder.toString(); | |
} | |
private void toString(StringBuilder builder, TimeUnit timeUnit, int level, String treeChar) | |
{ | |
for (int i = level; i > 0; i--) | |
{ | |
if (i == 1) builder.append(treeChar); | |
else builder.append("|"); | |
} | |
long actualElapsedNanos = isRunning ? System.nanoTime() - startNanoTime : elapsedNanos; | |
builder.append(name).append("[").append(Long.toString(timeUnit.convert(actualElapsedNanos, TimeUnit.NANOSECONDS))).append("]"); | |
builder.append("\n"); | |
StopWatchTree last = children.isEmpty() ? null : children.getLast(); | |
for (StopWatchTree child : children) | |
{ | |
child.toString(builder, timeUnit, level + 1, child == last ? "\\" : "+"); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment