001/* 002 * jPOS Project [http://jpos.org] 003 * Copyright (C) 2000-2026 jPOS Software SRL 004 * 005 * This program is free software: you can redistribute it and/or modify 006 * it under the terms of the GNU Affero General Public License as 007 * published by the Free Software Foundation, either version 3 of the 008 * License, or (at your option) any later version. 009 * 010 * This program is distributed in the hope that it will be useful, 011 * but WITHOUT ANY WARRANTY; without even the implied warranty of 012 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 013 * GNU Affero General Public License for more details. 014 * 015 * You should have received a copy of the GNU Affero General Public License 016 * along with this program. If not, see <http://www.gnu.org/licenses/>. 017 */ 018 019package org.jpos.util; 020 021import java.time.Duration; 022import java.time.Instant; 023import java.util.concurrent.atomic.AtomicReference; 024 025/** 026 * General purpose Chronometer 027 * 028 * Measures execution time (in millis) with support for partial durations. 029 */ 030public class Chronometer { 031 private final AtomicReference<Instant> start; 032 private final AtomicReference<Instant> lap; 033 034 /** 035 * Creates a new Chronometer 036 */ 037 public Chronometer() { 038 this (Instant.now()); 039 } 040 041 /** 042 * Creates a new Chronometer and specify start instant 043 * @param start chronometer start 044 */ 045 public Chronometer(Instant start) { 046 this.start = new AtomicReference<>(start); 047 this.lap = new AtomicReference<>(this.start.get()); 048 } 049 050 /** 051 * Returns elapsed time since creation or last reset 052 * 053 * @return elapsed time in millis 054 */ 055 public long elapsed() { 056 return Duration.between(start.get(), Instant.now()).toMillis(); 057 } 058 059 /** 060 * Resets this chronometer. 061 */ 062 public void reset() { 063 start.set(Instant.now()); 064 } 065 066 /** 067 * Ongoing partial since start or last lap. 068 * 069 * @return ongoing partial in millis. 070 */ 071 public long partial() { 072 return Duration.between(lap.get(), Instant.now()).toMillis(); 073 } 074 075 /** 076 * Return current partial and resets lap. 077 * 078 * @return partial in millis. 079 */ 080 public long lap() { 081 Instant now = Instant.now(); 082 long elapsed = Duration.between(lap.get(), now).toMillis(); 083 lap.set(now); 084 return elapsed; 085 } 086 087 @Override 088 public String toString() { 089 return "Chronometer{" + 090 "elapsed=" + elapsed() + 091 ", lap=" + (Duration.between(lap.get(), Instant.now()).toMillis()) + 092 '}'; 093 } 094}