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 Lesser 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 Lesser General Public License for more details. 018 * 019 * You should have received a copy of the GNU Lesser 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 import edu.umd.cs.findbugs.annotations.NonNull; 033 034 public class Timer { 035 @NonNull public static final Logger logger = Logger.getLogger( Timer.class ); 036 @NonNull private static final DecimalFormat numberFormatter = new DecimalFormat("#.##"); 037 038 private boolean running; 039 private long startNanos; 040 private long elapsedNanoseconds; 041 042 public Timer() { 043 restart(); 044 } 045 046 public void restart() { 047 this.running = true; 048 this.elapsedNanoseconds = 0; 049 this.startNanos = System.nanoTime() ; 050 } 051 052 public void stop() { 053 assert isRunning(); 054 055 this.running = false; 056 this.elapsedNanoseconds = System.nanoTime() - this.startNanos; 057 } 058 059 public boolean isRunning() { 060 return this.running; 061 } 062 063 public long getElapsedMicroseconds() { 064 assert !isRunning(); 065 066 long result = this.elapsedNanoseconds / 1000; 067 return result; 068 } 069 070 public long getElapsedMilliseconds() { 071 assert !isRunning(); 072 073 return getElapsedMicroseconds() / 1000; 074 } 075 076 public void logDebugTimeInMilliseconds( String message ) { 077 assert !StringUtils.isEmpty(message); 078 assert !isRunning(); 079 080 if( logger.isDebugEnabled() ) { 081 logger.debug( message + ": " + numberFormatter.format(getElapsedMicroseconds() / 1000.0)+ " ms." ); 082 } 083 } 084 }