001/** 002 * 003 * Copyright (c) 2014, the Railo Company Ltd. All rights reserved. 004 * 005 * This library is free software; you can redistribute it and/or 006 * modify it under the terms of the GNU Lesser General Public 007 * License as published by the Free Software Foundation; either 008 * version 2.1 of the License, or (at your option) any later version. 009 * 010 * This library is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU 013 * Lesser General Public License for more details. 014 * 015 * You should have received a copy of the GNU Lesser General Public 016 * License along with this library. If not, see <http://www.gnu.org/licenses/>. 017 * 018 **/ 019package lucee.runtime.timer; 020 021/** 022 * Implementation of a simple Stopwatch 023 */ 024public class Stopwatch { 025 026 public static final int UNIT_MILLI=1; 027 public static final int UNIT_NANO=2; 028 //public static final int UNIT_MICRO=4; 029 030 031 private long start; 032 private int count=0; 033 private long total=0; 034 boolean isRunning; 035 private boolean useNano; 036 037 038 public Stopwatch(int unit){ 039 useNano=unit==UNIT_NANO; 040 } 041 042 /** 043 * start the watch 044 */ 045 public void start() { 046 isRunning=true; 047 start=_time(); 048 } 049 050 private long _time() { 051 return useNano?System.nanoTime():System.currentTimeMillis(); 052 } 053 054 /** 055 * stops the watch 056 * @return returns the current time or 0 if watch not was running 057 */ 058 public long stop() { 059 if(isRunning) { 060 long time=_time()-start; 061 total+=time; 062 count++; 063 isRunning=false; 064 return time; 065 066 } 067 return 0; 068 } 069 070 /** 071 * @return returns the current time or 0 if watch is not running 072 */ 073 public long time() { 074 if(isRunning)return _time()-start; 075 return 0; 076 } 077 078 /** 079 * @return returns the total elapsed time 080 */ 081 public long totalTime() { 082 return total+time(); 083 } 084 085 /** 086 * @return returns how many start and stop was making 087 */ 088 public int count() { 089 return count; 090 } 091 /** 092 * resets the stopwatch 093 */ 094 public void reset() { 095 start=0; 096 count=0; 097 total=0; 098 isRunning=false; 099 } 100}