001/** 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.camel.util; 018 019import java.util.Date; 020 021/** 022 * A very simple stop watch. 023 * <p/> 024 * This implementation is not thread safe and can only time one task at any given time. 025 * 026 * @version 027 */ 028public final class StopWatch { 029 030 private long start; 031 032 /** 033 * Starts the stop watch 034 */ 035 public StopWatch() { 036 this.start = System.currentTimeMillis(); 037 } 038 039 /** 040 * Starts the stop watch from the given timestamp 041 */ 042 public StopWatch(Date startTimestamp) { 043 start = startTimestamp.getTime(); 044 } 045 046 /** 047 * Creates the stop watch 048 * 049 * @param start whether it should start immediately 050 */ 051 public StopWatch(boolean start) { 052 if (start) { 053 this.start = System.currentTimeMillis(); 054 } 055 } 056 057 /** 058 * Starts or restarts the stop watch 059 */ 060 public void restart() { 061 start = System.currentTimeMillis(); 062 } 063 064 /** 065 * Reports the time taken (does not stop the stop watch) 066 * 067 * @return the time taken in millis. 068 * @deprecated use {@link #taken()} 069 */ 070 @Deprecated 071 public long stop() { 072 return taken(); 073 } 074 075 /** 076 * Returns the time taken in millis. 077 * 078 * @return time in millis, or <tt>0</tt> if not started yet. 079 */ 080 public long taken() { 081 if (start > 0) { 082 return System.currentTimeMillis() - start; 083 } else { 084 return 0; 085 } 086 } 087 088}