Skip to content

Instantly share code, notes, and snippets.

@SatyaSnehith
Created February 4, 2021 14:40
Show Gist options
  • Save SatyaSnehith/e4fb2d92cfd6a22fb181d5292912f618 to your computer and use it in GitHub Desktop.
Save SatyaSnehith/e4fb2d92cfd6a22fb181d5292912f618 to your computer and use it in GitHub Desktop.
find out the execution time of a block of code or whole program
public class ExecutionTimer {
private static long startTime;
static {
startTime = -1;
}
public static void startTimer() {
startTime = System.currentTimeMillis();
}
public static String getTimeFromMillis(long millis) {
String time = "";
long seconds = millis / 1000;
long minutes = seconds / 60;
long hours = minutes / 60;
long days = hours / 24;
long months = days / 30;
long years = months / 12;
if (years > 0) {
time += years + " year" + (years > 1 ? "s " : " ");
}
if (months > 0) {
long mnths = (months % 12);
if (mnths > 0) {
time += mnths + " month" + (mnths > 1 ? "s " : " ");
}
}
if (days > 0) {
long dys = (days % 30);
if (dys > 0) {
time += dys + " day" + (dys > 1 ? "s " : " ");
}
}
if (hours > 0) {
long hrs = (hours % 24);
if (hrs > 0) {
time += hrs + " hour" + (hrs > 1 ? "s " : " ");
}
}
if (minutes > 0) {
long mins = (minutes % 60);
if (mins > 0) {
time += mins + " minute" + (mins > 1 ? "s " : " ");
}
}
if (seconds > 0) {
long secs = (seconds % 60);
if (secs > 0) {
time += secs + " second" + (secs > 1 ? "s " : " ");
}
}
time += (millis % 1000) + " millis";
return time;
}
public static String stopTimer() {
if (startTime == -1) return "please start the timer";
return getTimeFromMillis(System.currentTimeMillis() - startTime);
}
public static void main(String[] args) {
System.out.println(getTimeFromMillis(System.currentTimeMillis()));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment