001/* Copyright (C) 2013 TU Dortmund
002 * This file is part of LearnLib, http://www.learnlib.de/.
003 * 
004 * LearnLib is free software; you can redistribute it and/or
005 * modify it under the terms of the GNU Lesser General Public
006 * License version 3.0 as published by the Free Software Foundation.
007 * 
008 * LearnLib is distributed in the hope that it will be useful,
009 * but WITHOUT ANY WARRANTY; without even the implied warranty of
010 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
011 * Lesser General Public License for more details.
012 * 
013 * You should have received a copy of the GNU Lesser General Public
014 * License along with LearnLib; if not, see
015 * <http://www.gnu.de/documents/lgpl.en.html>.
016 */
017
018package de.learnlib.statistics;
019
020import de.learnlib.logging.LearnLogger;
021import java.util.HashMap;
022import java.util.Map;
023import java.util.Map.Entry;
024
025/**
026 * Very rudimentary profiler. 
027 */
028public class SimpleProfiler {
029
030  private static boolean PROFILE = true;
031  
032  private static final Map<String,Counter> cumulated = new HashMap<>();
033  private static final Map<String,Long> pending = new HashMap<>();
034   
035  private static LearnLogger logger = LearnLogger.getLogger(SimpleProfiler.class.getName());
036  
037  /**
038   * reset internal data.
039   */
040  public static void reset() {
041      cumulated.clear();
042      pending.clear();
043  }
044  
045  /**
046   * start activity.
047   * 
048   * @param name 
049   */
050  public static void start(String name) {
051    if (!PROFILE) {
052      return;
053    }
054    long start = System.currentTimeMillis();
055  
056    pending.put(name,start);
057    
058  }
059  
060  /**
061   * stop activity.
062   * 
063   * @param name 
064   */
065  public static void stop(String name) {
066    if (!PROFILE) {
067      return;
068    }
069    Long start = pending.remove(name);
070    if (start == null) {
071      return;
072    }
073    long duration = System.currentTimeMillis() - start;
074    Counter sum = cumulated.get(name);
075    if (sum == null) {
076      sum = new Counter(name, "ms");
077    }
078    sum.increment(duration);
079    cumulated.put(name, sum);
080  }
081  
082  /**
083   * get profiling results as string.
084   * 
085   * @return 
086   */
087  public static String getResults() {
088    StringBuilder sb = new StringBuilder();
089    for (Entry<String, Counter> e : cumulated.entrySet()) {
090        sb.append(e.getValue().getSummary()).append(", (").append(e.getValue().getCount()/1000.0).
091                append(" s)").append(System.lineSeparator());
092    }
093    return sb.toString();
094  }
095  
096  /**
097   * log results in category PROFILING.
098   */
099  public static void logResults() {
100    for (Entry<String, Counter> e : cumulated.entrySet()) {
101      logger.logProfilingInfo(e.getValue());
102    }  
103  }
104  
105}