001package io.prometheus.metrics.core.datapoints;
002
003import io.prometheus.metrics.model.snapshots.Unit;
004import java.io.Closeable;
005import java.util.function.DoubleConsumer;
006
007/** Helper class for observing durations. */
008public class Timer implements Closeable {
009
010  private final DoubleConsumer observeFunction;
011  private final long startTimeNanos = System.nanoTime();
012
013  /**
014   * Constructor is package private. Use the {@link TimerApi} provided by the implementation of the
015   * {@link DataPoint}.
016   */
017  Timer(DoubleConsumer observeFunction) {
018    this.observeFunction = observeFunction;
019  }
020
021  /**
022   * Records the observed duration in seconds since this {@code Timer} instance was created.
023   *
024   * @return the observed duration in seconds.
025   */
026  public double observeDuration() {
027    double elapsed = Unit.nanosToSeconds(System.nanoTime() - startTimeNanos);
028    observeFunction.accept(elapsed);
029    return elapsed;
030  }
031
032  /** Same as {@link #observeDuration()}. */
033  @Override
034  public void close() {
035    observeDuration();
036  }
037}