public class PerformanceMeasurementUtil {
private static final Map<String, Long> accruedTimeMap = new ConcurrentHashMap<>();
private static final Map<String, Long> startTimeMap = new ConcurrentHashMap<>();
private static final Logger logger = LoggerFactory.getLogger(PerformanceMeasurementUtil.class);
private static final String MSG_TOTAL_TIME = "Performance Measurement Results in Thread %d:----The total time for key %s is %d";
private static final String MSG_START_TIME = "Performance Measurement Start Time in Thread %d: The start time for key %s is %d";
private static final String MSG_END_TIME = "Performance Measurement End Time in Thread %d:---The end time for key %s is %d";
public static void recordStartTime(String measurementKey) {
Long now = System.currentTimeMillis();
startTimeMap.put(measurementKey, now);
//logger.error(String.format(MSG_START_TIME, Thread.currentThread().getId(), measurementKey, now));
}
public static void recordEndTime(String measurementKey) {
long now = System.currentTimeMillis();
//logger.error(String.format(MSG_END_TIME, Thread.currentThread().getId(), measurementKey, now));
Long startTime = startTimeMap.get(measurementKey);
long consumedTime = now - startTime;
Long accruedTime = accruedTimeMap.get(measurementKey);
Long totalTime = add(accruedTime, consumedTime);
accruedTimeMap.put(measurementKey, totalTime);
}
private static Long add(Long accruedTime, long consumedTime) {
return accruedTime == null ? consumedTime : accruedTime + consumedTime;
}
public static void printMeasurements() {
for (Map.Entry<String, Long> entry : accruedTimeMap.entrySet()) {
logger.error(String.format(MSG_TOTAL_TIME, Thread.currentThread().getId(), entry.getKey(), entry.getValue()));
}
}
public static void log(String msg) {
logger.error(String.format("Log msg in Thread %d: %s", Thread.currentThread().getId(), msg));
}
public static void reset() {
logger.error("time has been cleared");
startTimeMap.clear();
accruedTimeMap.clear();
}
}