001 /* 002 * StopWatch.java 003 * 004 * Created on September 25, 2003, 1:53 PM 005 */ 006 007 package cs101.util; 008 009 /** 010 * A stopwatch for timing the execution of code. This class is intended to 011 * provide aproximate time of execution to a resolution of single digit 012 * miliseconds on most modern machines. Estimates of cost on a dual 013 * Athlon MP 2000+ machien yeild the following costs for the following methods 014 * <ul> 015 * <li><code>start()</code> takes aprox 0.000269 seconds 016 * <li><code>stop()</code> takes aprox 0.000570 seconds 017 * <li><code>reset()</code> takes aprox 0.000274 seconds 018 * <li><code>elapsed()</code> takes aprox 0.000278 seconds (stopped) 019 * <li><code>look()</code> takes aprox 0.006071 seconds(stopped) 020 * <li><code>elapsed()</code> takes aprox 0.000285 seconds (running) 021 * <li><code>look()</code> takes aprox 0.006209 seconds (running) 022 * </ul> 023 * 024 * @author Gus Heck (gus.heck@olin.edu) 025 * @version $Id: StopWatch.java,v 1.1 2003/10/16 20:40:51 gus Exp $ 026 */ 027 public class StopWatch { 028 029 public static long MS_SEC = 1000l; 030 public static long MS_MIN = 60000l; 031 public static long MS_HOUR = 3600000l; 032 033 private long started; 034 private long startedFrom; 035 private long stopped; 036 private boolean running; 037 038 /** Creates a new instance of StopWatch. */ 039 public StopWatch() { 040 stop(); 041 reset(); 042 } 043 044 /** 045 * Start the stopwatch. 046 */ 047 public void start() { 048 running = true; 049 started = System.currentTimeMillis(); 050 } 051 052 /** 053 * Stop the stopwatch. 054 */ 055 public void stop() { 056 stopped = System.currentTimeMillis(); 057 running = false; 058 startedFrom = elapsed(); 059 } 060 061 /** 062 * Reset the stopwatch. It is perfectly legal and reasonable to 063 * reset the stopwatch while it is still running. The elapsed time on 064 * the stopwatch is set to 0 regardless. 065 */ 066 public void reset() { 067 stopped = started = System.currentTimeMillis(); 068 startedFrom = 0; 069 } 070 071 public long elapsed() { 072 long time = System.currentTimeMillis(); 073 return ((running ? time : stopped) - started) 074 + startedFrom; 075 } 076 077 public String look() { 078 StringBuffer elapsedTime = new StringBuffer(); 079 080 long time = elapsed(); 081 long ms = time % MS_SEC; 082 long sec = (time % MS_MIN)/MS_SEC; 083 long min = (time % MS_HOUR)/MS_MIN; 084 long hour = time/MS_HOUR; 085 086 elapsedTime.append(hour + " hours "); 087 elapsedTime.append(min + " minutes "); 088 elapsedTime.append(sec + "." + ms + " seconds "); 089 elapsedTime.append("have elapsed."); 090 091 return elapsedTime.toString(); 092 } 093 }