001// License: GPL. For details, see LICENSE file. 002package org.openstreetmap.josm.tools; 003 004import static org.openstreetmap.josm.tools.I18n.tr; 005 006/** 007 * Measures elapsed time in milliseconds 008 * 009 * @see <a href="https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/base/Stopwatch.html">Stopwatch in Guava</a> 010 * @since 15755 011 */ 012public final class Stopwatch { 013 private final long start; 014 015 private Stopwatch(long start) { 016 this.start = start; 017 } 018 019 /** 020 * Creates and starts a stopwatch 021 * 022 * @return the started stopwatch 023 */ 024 public static Stopwatch createStarted() { 025 return new Stopwatch(System.nanoTime()); 026 } 027 028 /** 029 * Returns the elapsed milliseconds 030 * 031 * @return the elapsed milliseconds 032 */ 033 public long elapsed() { 034 return (System.nanoTime() - start) / 1_000_000; 035 } 036 037 /** 038 * Formats the duration since start as string 039 * 040 * @return the duration since start as string 041 * @see Utils#getDurationString(long) 042 */ 043 @Override 044 public String toString() { 045 // fix #11567 where elapsedTime is < 0 046 return Utils.getDurationString(Math.max(0, elapsed())); 047 } 048 049 /** 050 * Formats the given task name and duration since start as i18n string 051 * @param taskName the task name 052 * @return the task name and duration since start as i18n string 053 */ 054 public String toString(String taskName) { 055 return tr("{0} completed in {1}", taskName, toString()); 056 } 057}