All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.databasesandlife.util.Timer Maven / Gradle / Ivy

There is a newer version: 21.0.1
Show newest version
package com.databasesandlife.util;

import java.util.HashMap;
import java.util.Locale;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * Times a calculation.
 *    

* Usage: *

try (Timer ignored = new Timer("doing something")) { ... }
* * @author This source is copyright Adrian Smith and licensed under the LGPL 3. * @see Project on GitHub */ public class Timer implements AutoCloseable { static Logger logger = LoggerFactory.getLogger(Timer.class); static ThreadLocal> start = new ThreadLocal<>(); protected static String getPrefix() { var count = start.get().size(); if (count >= 10) { return "I x"+count+" "; } else { return "I ".repeat(count); } } /** @deprecated use try (Timer ignored = new Timer("...")) { .. } instead */ @Deprecated public static void start(String name) { if (start.get() == null) start.set(new HashMap()); if (start.get().containsKey(name)) { logger.warn("Timer start '"+name+"' but this name is already active"); return; } logger.info(getPrefix() + "'" + name + "' start"); start.get().put(name, System.nanoTime()); } public static String formatDurationNanos(long durationNanoSeconds) { var seconds = durationNanoSeconds / (1000*1000*1000.0); var minutes = (int) seconds / 60; seconds -= 60 * minutes; var hours = (int) minutes / 60; minutes -= 60 * hours; var hoursStr = (hours == 0) ? "" : (hours + " hrs "); var minutesStr = (hours == 0 && minutes == 0) ? "" : (minutes + " min "); return String.format(Locale.ENGLISH, "%s%s%.3f sec", hoursStr, minutesStr, seconds); } /** @deprecated use try (Timer ignored = new Timer("...")) { .. } instead */ @Deprecated public static void end(String name) { if (start.get() == null) start.set(new HashMap()); if ( ! start.get().containsKey(name)) { logger.warn("Timer end '" + name + "' but was never started"); return; } var durationNanos = System.nanoTime() - start.get().get(name); start.get().remove(name); logger.info(String.format("%s'%s' end (%s)", getPrefix(), name, formatDurationNanos(durationNanos))); } protected String name; public Timer(String x) { Timer.start(name = x); } @Override public void close() { Timer.end(name); } }




© 2015 - 2024 Weber Informatics LLC | Privacy Policy