Last active
November 25, 2020 16:28
-
-
Save obrassard/43ad74aff12045f84c16148e85f339cb to your computer and use it in GitHub Desktop.
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
package LOG320.labo3.helpers; | |
import java.util.Collections; | |
import java.util.Map; | |
import java.util.TreeMap; | |
import java.util.concurrent.TimeUnit; | |
/** | |
* Forked from https://gist.github.com/juanmf/4147a9b7010c7b04c003 | |
*/ | |
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 long end(String name) { | |
Stopwatch task = RUNNING.get(name); | |
if (task == null) { | |
throw new IllegalArgumentException("no task after name: " + name); | |
} | |
task.end(); | |
long elapsedTime = task.getElapsedTime(); | |
System.out.println(name + " ended after : " + elapsedTime + " ms"); | |
RUNNING.remove(name); | |
return elapsedTime; | |
} | |
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; | |
} | |
private long getElapsedTime() { | |
if (startedAt == 0) { | |
throw new IllegalStateException("startedAt is not set."); | |
} | |
long end = endedAt != 0 ? endedAt : System.nanoTime(); | |
return TimeUnit.MILLISECONDS.convert(end - startedAt, TimeUnit.NANOSECONDS); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment