001    package railo.runtime.timer;
002    
003    /**
004     * Implementation of a simple Stopwatch
005     */
006    public class Stopwatch {
007    
008            public static final int UNIT_MILLI=1;
009            public static final int UNIT_NANO=2;
010            //public static final int UNIT_MICRO=4;
011            
012            
013            private long start;
014            private int count=0;
015            private long total=0;
016            boolean isRunning;
017            private boolean useNano;
018            
019            
020            public Stopwatch(int unit){
021                    useNano=unit==UNIT_NANO;
022            }
023            
024            /**
025             * start the watch
026             */
027            public void start() {
028                    isRunning=true;
029                    start=_time();
030            }
031            
032            private long _time() {
033                    return useNano?System.nanoTime():System.currentTimeMillis();
034            }
035    
036            /**
037             * stops the watch
038             * @return returns the current time or 0 if watch not was running
039             */
040            public long stop() {
041                    if(isRunning) {
042                            long time=_time()-start;
043                            total+=time;
044                            count++;
045                            isRunning=false;
046                            return time;
047                            
048                    }
049                    return 0;
050            }
051            
052            /**
053             * @return returns the current time or 0 if watch is not running
054             */
055            public long time() {
056                    if(isRunning)return _time()-start;
057                    return 0;
058            }
059            
060            /**
061             * @return returns the total elapsed time
062             */
063            public long totalTime() {
064                    return total+time();
065            }
066            
067            /**
068             * @return returns how many start and stop was making
069             */
070            public int count() {
071                    return count;
072            }
073            /**
074             * resets the stopwatch
075             */
076            public void reset() {
077                    start=0;
078                    count=0;
079                    total=0;
080                    isRunning=false;
081            }
082    }