001package org.hl7.fhir.utilities; 002 003import java.util.ArrayList; 004import java.util.HashMap; 005import java.util.List; 006import java.util.Map; 007 008import org.hl7.fhir.utilities.TimeTracker.Counter; 009 010public class TimeTracker { 011 012 public class Counter { 013 private String name; 014 private int count; 015 private long length; 016 public Counter(String name) { 017 this.name = name; 018 } 019 } 020 021 public class Session { 022 private long start = System.nanoTime(); 023 private String name; 024 public Session(String name) { 025 this.name = name; 026 } 027 public void end() { 028 endSession(this); 029 } 030 } 031 032 private List<Session> sessions = new ArrayList<>(); 033 private List<Counter> records = new ArrayList<>(); 034 private long globalStart; 035 private long milestone = 0; 036 037 038 public TimeTracker() { 039 super(); 040 globalStart = System.nanoTime(); 041 } 042 043 public Session start(String name) { 044 Counter c = null; 045 for (Counter t : records) { 046 if (t.name.equals(name)) { 047 c = t; 048 } 049 } 050 if (c == null) { 051 c = new Counter(name); 052 records.add(c); 053 } 054 Session session = new Session(name); 055 sessions.add(session); 056 return session; 057 } 058 059 private void endSession(Session session) { 060 sessions.remove(session); 061 Counter c = null; 062 for (Counter t : records) { 063 if (t.name.equals(session.name)) { 064 c = t; 065 } 066 } 067 c.count++; 068 c.length = c.length + System.nanoTime() - session.start; 069 } 070 071 public String report() { 072 CommaSeparatedStringBuilder b = new CommaSeparatedStringBuilder(); 073 for (Counter c : records) { 074 if (c.count == 1) { 075 b.append(c.name+": "+Utilities.presentDuration(c.length)); 076 } 077 } 078 for (Counter c : records) { 079 if (c.count > 1) { 080 b.append(c.name+": "+Utilities.presentDuration(c.length)+" (#"+c.count+")"); 081 } 082 } 083 return "Times: "+b.toString(); 084 } 085 086 public String clock() { 087 return Utilities.presentDuration(System.nanoTime() - globalStart); 088 } 089 090 public String instant() { 091 return Utilities.presentDuration(System.nanoTime() - globalStart); 092 } 093 094 public String milestone() { 095 long start = milestone == 0 ? globalStart : milestone ; 096 milestone = System.nanoTime(); 097 return Utilities.presentDuration(milestone - start); 098 } 099 100}