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.time.Duration;
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 */
026public final class StopWatch {
027
028    private long start;
029
030    /**
031     * Starts the stop watch
032     */
033    public StopWatch() {
034        this.start = System.nanoTime();
035    }
036
037    /**
038     * Starts the stop watch from the given timestamp
039     */
040    @Deprecated
041    public StopWatch(long timeMillis) {
042        start = Duration.ofMillis(timeMillis).toNanos();
043    }
044
045    /**
046     * Creates the stop watch
047     *
048     * @param start whether it should start immediately
049     */
050    public StopWatch(boolean start) {
051        if (start) {
052            this.start = System.nanoTime();
053        }
054    }
055
056    /**
057     * Starts or restarts the stop watch
058     */
059    public void restart() {
060        start = System.nanoTime();
061    }
062
063    /**
064     * Whether the watch is started
065     */
066    public boolean isStarted() {
067        return start > 0;
068    }
069
070    /**
071     * Returns the time taken in millis.
072     *
073     * @return time in millis, or <tt>0</tt> if not started yet.
074     */
075    public long taken() {
076        if (start > 0) {
077            long delta = System.nanoTime() - start;
078            return Duration.ofNanos(delta).toMillis();
079        }
080        return 0;
081    }
082
083    /**
084     * Returns the time taken in millis and restarts the timer.
085     *
086     * @return time in millis, or <tt>0</tt> if not started yet.
087     */
088    public long takenAndRestart() {
089        long answer = taken();
090        start = System.nanoTime();
091        return answer;
092    }
093
094}