001    /*
002     * Copyright © 2008, 2009 Pedro Agulló Soliveres.
003     * 
004     * This file is part of DirectJNgine.
005     *
006     * DirectJNgine is free software: you can redistribute it and/or modify
007     * it under the terms of the GNU General Public License as published by
008     * the Free Software Foundation, either version 3 of the License.
009     *
010     * Commercial use is permitted to the extent that the code/component(s)
011     * do NOT become part of another Open Source or Commercially developed
012     * licensed development library or toolkit without explicit permission.
013     *
014     * DirectJNgine is distributed in the hope that it will be useful,
015     * but WITHOUT ANY WARRANTY; without even the implied warranty of
016     * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
017     * GNU General Public License for more details.
018     *
019     * You should have received a copy of the GNU General Public License
020     * along with DirectJNgine.  If not, see <http://www.gnu.org/licenses/>.
021     * 
022     * This software uses the ExtJs library (http://extjs.com), which is 
023     * distributed under the GPL v3 license (see http://extjs.com/license).
024     */
025    
026    package com.softwarementors.extjs.djn;
027    
028    import java.text.DecimalFormat;
029    
030    import org.apache.log4j.Logger;
031    
032    public class Timer {
033      private static final Logger logger = Logger.getLogger( Timer.class );
034      private static final DecimalFormat numberFormatter = new DecimalFormat("#.##");
035    
036      private boolean running;  
037      private long startNanos;
038      private long elapsedNanoseconds;
039      
040      public Timer() {
041        restart();
042      }
043      
044      public void restart() {
045        this.running = true;
046        this.elapsedNanoseconds = 0;
047        this.startNanos = System.nanoTime() ; 
048      }
049      
050      public void stop() {
051        assert isRunning();
052        
053        this.running = false;
054        this.elapsedNanoseconds = System.nanoTime() - this.startNanos;
055      }
056      
057      public boolean isRunning() {
058        return this.running;
059      }
060      
061      public long getElapsedMicroseconds() {
062        assert !isRunning();
063        
064        long result = this.elapsedNanoseconds / 1000;
065        return result;
066      }
067      
068      public long getElapsedMilliseconds() {
069        assert !isRunning();
070    
071        return getElapsedMicroseconds() / 1000;
072      }
073      
074      public void logDebugTimeInMilliseconds( String message ) {
075        assert !StringUtils.isEmpty(message);
076        assert !isRunning();
077      
078        if( logger.isDebugEnabled() ) {
079          logger.debug( message + ": " + numberFormatter.format(getElapsedMicroseconds() / 1000.0)+ " ms." );
080        }
081      }
082    }