Last active
March 24, 2019 16:28
-
-
Save juanmf/4147a9b7010c7b04c003 to your computer and use it in GitHub Desktop.
Simple Stopwatch that keeps a cache of running tasks.
This file contains hidden or 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.Collections; | |
import java.util.Map; | |
import java.util.TreeMap; | |
/** | |
* Usage: | |
* | |
* Stopwatch.start("watchName"); | |
* ... | |
* Stopwatch.end("watchName"); | |
* | |
* Stopwatch.start("loadingResource"); | |
* ... | |
* Stopwatch.end("loadingResource"); | |
* ... | |
* | |
* Stopwatch.getRunning().entrySet().stream().forEach(e -> { | |
* System.out.println(e.getKey() + " => nanos: " + e.getValue().getElapsedTime()); | |
* }); | |
* | |
* Output would be: | |
* | |
* InitComparator => nanos: 1800910 | |
* loadingAgainstPattern => nanos: 187572841 | |
* loadingResources => nanos: 1013792631 | |
* sorting => nanos: 3599532 | |
* | |
* @author juan.fernandez | |
*/ | |
public class Stopwatch { | |
private static final Map<String, Stopwatch> RUNNING = new TreeMap<>(); | |
private long startedAt; | |
private long endedAt; | |
public static Map<String, Stopwatch> getRunning() { | |
return Collections.unmodifiableMap(RUNNING); | |
} | |
public static void start(String name) { | |
RUNNING.put(name, new Stopwatch().start()); | |
} | |
public static void end(String name) { | |
Stopwatch task = RUNNING.get(name); | |
if (task == null) { | |
throw new IllegalArgumentException("no task aftre name: " + name); | |
} | |
task.end(); | |
} | |
public static long getElapsedTime(String name) { | |
Stopwatch task = RUNNING.get(name); | |
if (task == null) { | |
throw new IllegalArgumentException("no task after name: " + name); | |
} | |
return task.getElapsedTime(); | |
} | |
private Stopwatch start() { | |
startedAt = System.nanoTime(); | |
return this; | |
} | |
private Stopwatch end() { | |
endedAt = System.nanoTime(); | |
return this; | |
} | |
public long getElapsedTime() { | |
if (endedAt == 0 || startedAt == 0) { | |
throw new IllegalStateException("either startedAt or endedAt are not set."); | |
} | |
return endedAt - startedAt; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment