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     */
017    package org.apache.camel.util;
018    
019    import 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     */
028    public final class StopWatch {
029    
030        private long start;
031        private long stop;
032    
033        /**
034         * Starts the stop watch
035         */
036        public StopWatch() {
037            this(true);
038        }
039    
040        /**
041         * Starts the stop watch from the given timestamp
042         */
043        public StopWatch(Date startTimestamp) {
044            start = startTimestamp.getTime();
045        }
046    
047        /**
048         * Creates the stop watch
049         *
050         * @param started whether it should start immediately
051         */
052        public StopWatch(boolean started) {
053            if (started) {
054                restart();
055            }
056        }
057    
058        /**
059         * Starts or restarts the stop watch
060         */
061        public void restart() {
062            start = System.currentTimeMillis();
063            stop = 0;
064        }
065    
066        /**
067         * Stops the stop watch
068         *
069         * @return the time taken in millis.
070         */
071        public long stop() {
072            stop = System.currentTimeMillis();
073            return taken();
074        }
075    
076        /**
077         * Returns the time taken in millis.
078         *
079         * @return time in millis
080         */
081        public long taken() {
082            if (start > 0 && stop > 0) {
083                return stop - start;
084            } else if (start > 0) {
085                return System.currentTimeMillis() - start;
086            } else {
087                return 0;
088            }
089        }
090    
091    }