Skip to content

Instantly share code, notes, and snippets.

@igorokr
Created July 28, 2015 00:25
Show Gist options
  • Save igorokr/44e86420dc56dafdd708 to your computer and use it in GitHub Desktop.
Save igorokr/44e86420dc56dafdd708 to your computer and use it in GitHub Desktop.
Helper class to measure execution time in java code
import java.util.concurrent.TimeUnit;
/**
* Helper class to measure execution time in java code
*
* Usage:
*
* public static void main(String[] args) {
* MeasureExecTimeHelper.start();
* staffToMeasureExecTime();
* System.out.println(MeasureExecTimeHelper.stopAndResult_Millis());
* }
*
* igorok.r<a>gmail.com
*/
public class MeasureExecTimeHelper {
private static final String TEMPLATE_MS = " %s ms ";
private static final String TEMPLATE_NS = " %s ns ";
private static long startTime = 0;
private static boolean inProgress = false;
public static void start() {
inProgress = true;
startTime = System.nanoTime();
}
private static long calcDurationNano() {
long endTime = System.nanoTime();
return endTime - startTime;
}
private static void markStoppedOrException() {
if (inProgress) {
inProgress = false;
} else {
throw new IllegalStateException(" Already stopped. Looks like you called result method more than 1 time! ");
}
}
public static long stopAndResultNano() {
markStoppedOrException();
return calcDurationNano();
}
public static String stopAndResult_Millis() {
markStoppedOrException();
return String.format(TEMPLATE_MS, TimeUnit.MILLISECONDS.convert(calcDurationNano(), TimeUnit.NANOSECONDS));
}
public static String stopAndResult_Nanos() {
markStoppedOrException();
return String.format(TEMPLATE_NS, calcDurationNano());
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment