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 /**
020 * A very simple stop watch.
021 * <p/>
022 * This implementation is not thread safe and can only time one task at any given time.
023 *
024 * @version
025 */
026 public final class StopWatch {
027
028 private long start;
029 private long stop;
030
031 /**
032 * Starts the stop watch
033 */
034 public StopWatch() {
035 this(true);
036 }
037
038 /**
039 * Creates the stop watch
040 *
041 * @param started whether it should start immediately
042 */
043 public StopWatch(boolean started) {
044 if (started) {
045 restart();
046 }
047 }
048
049 /**
050 * Starts or restarts the stop watch
051 */
052 public void restart() {
053 start = System.currentTimeMillis();
054 stop = 0;
055 }
056
057 /**
058 * Stops the stop watch
059 *
060 * @return the time taken in millis.
061 */
062 public long stop() {
063 stop = System.currentTimeMillis();
064 return taken();
065 }
066
067 /**
068 * Returns the time taken in millis.
069 *
070 * @return time in millis
071 */
072 public long taken() {
073 if (start > 0 && stop > 0) {
074 return stop - start;
075 } else if (start > 0) {
076 return System.currentTimeMillis() - start;
077 } else {
078 return 0;
079 }
080 }
081
082 }