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