diff --git hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/MonotonicClock.java hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/MonotonicClock.java new file mode 100644 index 0000000..f1f0a7d --- /dev/null +++ hadoop-yarn-project/hadoop-yarn/hadoop-yarn-common/src/main/java/org/apache/hadoop/yarn/util/MonotonicClock.java @@ -0,0 +1,67 @@ +/** + * Licensed to the Apache Software Foundation (ASF) under one + * or more contributor license agreements. See the NOTICE file + * distributed with this work for additional information + * regarding copyright ownership. The ASF licenses this file + * to you under the Apache License, Version 2.0 (the + * "License"); you may not use this file except in compliance + * with the License. You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + */ +package org.apache.hadoop.yarn.util; + +/** + * Implementation of {@link Clock} that can be used to measure a period of time. + */ +public class MonotonicClock implements Clock{ + + private static final long NANOSECONDS_PER_MILLISECOND = 1000000; + private static final long gap; + + private long start = -1; + private boolean timing = false; + + static { + gap = System.nanoTime() / NANOSECONDS_PER_MILLISECOND - System.currentTimeMillis(); + } + + /** + * Get time from the clock. The time is ensured to be monotonic, which means + * it is not disturbed when JVM is running. The clock is calibrated with the + * System clock when the class is loaded, but note that the returned value + * may be different with that get from System.currentTimeMills, because the + * latter may be updated by NTP. + * @return time in millisecond. + */ + @Override + public long getTime() { + return System.nanoTime() / NANOSECONDS_PER_MILLISECOND - gap; + } + + /** + * Start timing. + */ + public void start() { + timing = true; + this.start = getTime(); + } + + /** + * Stop timing and get the result. + * @return the interval in millisecond. + */ + public long stopAndGetInterval() { + if (timing == false) + throw new IllegalStateException("Method 'start()' should be called" + + " ahead of stopAndGetInterval"); + timing = false; + return getTime() - start; + } +}