A default Timer implementation that uses a Stopwatch instance internally to measure time.
| 33 | * measure time. |
| 34 | */ |
| 35 | public class DefaultTimer implements Timer { |
| 36 | private final TimeUnit timeUnit; |
| 37 | private final LongAdder count = new LongAdder(); |
| 38 | private final LongAdder totalTime = new LongAdder(); |
| 39 | |
| 40 | public DefaultTimer(TimeUnit timeUnit) { |
| 41 | Preconditions.checkArgument(null != timeUnit, "Invalid time unit: null"); |
| 42 | this.timeUnit = timeUnit; |
| 43 | } |
| 44 | |
| 45 | @Override |
| 46 | public long count() { |
| 47 | return count.longValue(); |
| 48 | } |
| 49 | |
| 50 | @Override |
| 51 | public Duration totalDuration() { |
| 52 | return Duration.ofNanos(totalTime.longValue()); |
| 53 | } |
| 54 | |
| 55 | @Override |
| 56 | public Timed start() { |
| 57 | return new DefaultTimed(this, timeUnit); |
| 58 | } |
| 59 | |
| 60 | @Override |
| 61 | public void record(long amount, TimeUnit unit) { |
| 62 | Preconditions.checkArgument(amount >= 0, "Cannot record %s %s: must be >= 0", amount, unit); |
| 63 | this.totalTime.add(TimeUnit.NANOSECONDS.convert(amount, unit)); |
| 64 | this.count.increment(); |
| 65 | } |
| 66 | |
| 67 | @Override |
| 68 | public <T> T time(Supplier<T> supplier) { |
| 69 | try (Timed ignore = start()) { |
| 70 | return supplier.get(); |
| 71 | } |
| 72 | } |
| 73 | |
| 74 | @Override |
| 75 | public <T> T timeCallable(Callable<T> callable) throws Exception { |
| 76 | try (Timed ignore = start()) { |
| 77 | return callable.call(); |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | @Override |
| 82 | public void time(Runnable runnable) { |
| 83 | try (Timed ignore = start()) { |
| 84 | runnable.run(); |
| 85 | } |
| 86 | } |
| 87 | |
| 88 | @Override |
| 89 | public TimeUnit unit() { |
| 90 | return timeUnit; |
| 91 | } |
| 92 |
nothing calls this directly
no outgoing calls
no test coverage detected