package tools; import java.util.*; public class HashTimer { private static Map __hitsCounters = new HashMap (); private static Map __timers = new HashMap (); public static void reset () { __hitsCounters = new HashMap (); __timers = new HashMap (); } public static void addTimeFor ( String i_key, final long timeIncrement ) { i_key = i_key.trim(); incHitsCounter(i_key); final long newValue = timeIncrement + totalTimeFor(i_key); __timers.put(i_key, new Long(newValue)); } public static int nofHitsFor ( String i_key) { Object o = __hitsCounters.get(i_key); if ( null == o ) { __hitsCounters.put(i_key, new Integer (0)); o = __hitsCounters.get(i_key); } final Integer integer = ( ( Integer ) o ); return integer.intValue(); } public static long totalTimeFor ( String i_key ) { Object o = __timers.get(i_key); if ( null == o ) { __timers.put(i_key, new Long(0)); o = __timers.get(i_key); } final Long aLong = ( ( Long ) o ); return aLong.longValue(); } private static void incHitsCounter (final String i_key) { final int value = 1 + nofHitsFor(i_key); __hitsCounters.put(i_key, new Integer(value)); } public static String results () { final Set keys = __hitsCounters.keySet(); if ( 0 == keys.size() ) { return "0 call - 0 ms"; } final int padLen = 1 + Util.longuestKeyLen( keys ); String result = ""; for ( Iterator iterator = keys.iterator(); iterator.hasNext(); ) { final String key = ( String) iterator.next() ; final int nofCalls = nofHitsFor(key) ; final long timeFor = totalTimeFor(key); if ( 1 <= nofCalls ) { result += Util.paddedText( key, padLen ) + ": " + nofCalls + " calls" + " - " + timeFor + " ms" + "\n"; } } return result ; } private static class Util { static int longuestKeyLen ( Set keys ) { int maxLen = 0; for ( Iterator iterator = keys.iterator(); iterator.hasNext(); ) { String key = ( String) iterator.next(); maxLen = Math.max( maxLen, key.length()); } return maxLen; } static String paddedText ( final String i_rawText, int i_minimumLen ) { StringBuffer result = new StringBuffer(i_minimumLen) ; result.append(i_rawText) ; for ( int i = i_rawText.length()+1; i <= i_minimumLen ; i++ ) { result.append(' ') ; } return result.toString(); } } }