forked from apache/commons-lang
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathStopWatch.java
More file actions
839 lines (765 loc) · 24.7 KB
/
StopWatch.java
File metadata and controls
839 lines (765 loc) · 24.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.commons.lang3.time;
import java.time.Duration;
import java.time.Instant;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;
import java.util.function.Supplier;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.function.FailableConsumer;
import org.apache.commons.lang3.function.FailableRunnable;
import org.apache.commons.lang3.function.FailableSupplier;
import org.apache.commons.lang3.tuple.ImmutablePair;
/**
* {@link StopWatch} provides a convenient API for timings.
*
* <p>
* To start the watch, call {@link #start()} or {@link StopWatch#createStarted()}. At this point you can:
* </p>
* <ul>
* <li>{@link #split()} the watch to get the time whilst the watch continues in the background. {@link #unsplit()} will remove the effect of the split. At this
* point, these three options are available again.</li>
* <li>{@link #suspend()} the watch to pause it. {@link #resume()} allows the watch to continue. Any time between the suspend and resume will not be counted in
* the total. At this point, these three options are available again.</li>
* <li>{@link #stop()} the watch to complete the timing session.</li>
* </ul>
*
* <p>
* It is intended that the output methods {@link #toString()} and {@link #getTime()} should only be called after stop, split or suspend, however a suitable
* result will be returned at other points.
* </p>
*
* <p>
* NOTE: As from v2.1, the methods protect against inappropriate calls. Thus you cannot now call stop before start, resume before suspend or unsplit before
* split.
* </p>
*
* <ol>
* <li>{@link #split()}, {@link #suspend()}, or {@link #stop()} cannot be invoked twice</li>
* <li>{@link #unsplit()} may only be called if the watch has been {@link #split()}</li>
* <li>{@link #resume()} may only be called if the watch has been {@link #suspend()}</li>
* <li>{@link #start()} cannot be called twice without calling {@link #reset()}</li>
* </ol>
*
* <p>
* This class is not thread-safe.
* </p>
*
* @see DurationUtils#of(FailableRunnable)
* @see DurationUtils#of(FailableConsumer)
* @since 2.0
*/
public class StopWatch {
/**
* Enumeration type which indicates the split status of a StopWatch.
*/
private enum SplitState {
SPLIT, UNSPLIT
}
/**
* Enumeration type which indicates the status of a StopWatch.
*/
private enum State {
RUNNING {
@Override
boolean isStarted() {
return true;
}
@Override
boolean isStopped() {
return false;
}
@Override
boolean isSuspended() {
return false;
}
},
STOPPED {
@Override
boolean isStarted() {
return false;
}
@Override
boolean isStopped() {
return true;
}
@Override
boolean isSuspended() {
return false;
}
},
SUSPENDED {
@Override
boolean isStarted() {
return true;
}
@Override
boolean isStopped() {
return false;
}
@Override
boolean isSuspended() {
return true;
}
},
UNSTARTED {
@Override
boolean isStarted() {
return false;
}
@Override
boolean isStopped() {
return true;
}
@Override
boolean isSuspended() {
return false;
}
};
/**
* Tests whether this StopWatch is started. A suspended StopWatch is also started.
*
* @return boolean If this StopWatch is started.
*/
abstract boolean isStarted();
/**
* Tests whether this StopWatch is stopped. A StopWatch which is not yet started and explicitly stopped is considered stopped.
*
* @return boolean If this StopWatch is stopped.
*/
abstract boolean isStopped();
/**
* Tests whether this StopWatch is suspended.
*
* @return boolean If this StopWatch is suspended.
*/
abstract boolean isSuspended();
}
private static final long NANO_2_MILLIS = 1_000_000L;
/**
* Creates a StopWatch.
*
* @return StopWatch a StopWatch.
* @since 3.10
*/
public static StopWatch create() {
return new StopWatch();
}
/**
* Creates and starts a StopWatch.
*
* @return StopWatch a started StopWatch.
* @since 3.5
*/
public static StopWatch createStarted() {
final StopWatch sw = new StopWatch();
sw.start();
return sw;
}
/**
* A message for string presentation.
*
* @since 3.10
*/
private final String message;
/**
* The current running state of this StopWatch.
*/
private State runningState = State.UNSTARTED;
/**
* Whether this StopWatch has a split time recorded.
*/
private SplitState splitState = SplitState.UNSPLIT;
/**
* The start time in nanoseconds.
*
* This field can be removed once we move off of Java 8.
*/
private long startTimeNanos;
/**
* The start Instant.
* <p>
* nanoTime is only for elapsed time so we need to also store the currentTimeMillis to maintain the old getStartTime API.
* </p>
* <p>
* On Java 8, Instant has millisecond precision, later versions use nanoseconds.
* </p>
*/
private Instant startInstant;
/**
* The end Instant.
* <p>
* nanoTime is only for elapsed time so we need to also store the currentTimeMillis to maintain the old getStartTime API.
* </p>
* <p>
* On Java 8, Instant has millisecond precision, later versions use nanoseconds.
* </p>
*/
private Instant stopInstant;
/**
* The stop time in nanoseconds.
*
* This field can be removed once we move off of Java 8.
*/
private long stopTimeNanos;
/**
* The split list.
*/
private final List<Split> splits = new ArrayList<>();
/**
* Constructs a new instance.
*/
public StopWatch() {
this(null);
}
/**
* Constructs a new instance.
*
* @param message A message for string presentation.
* @since 3.10
*/
public StopWatch(final String message) {
this.message = message;
}
/**
* Formats the split time with {@link DurationFormatUtils#formatDurationHMS}.
*
* @return the split time formatted by {@link DurationFormatUtils#formatDurationHMS}.
* @since 3.10
*/
public String formatSplitTime() {
return DurationFormatUtils.formatDurationHMS(getSplitDuration().toMillis());
}
/**
* Formats the time formatted with {@link DurationFormatUtils#formatDurationHMS}.
*
* @return the time formatted by {@link DurationFormatUtils#formatDurationHMS}.
* @since 3.10
*/
public String formatTime() {
return DurationFormatUtils.formatDurationHMS(getTime());
}
/**
* Delegates to {@link Supplier#get()} while recording the duration of the call.
*
* @param <T> the type of results supplied by this supplier.
* @param supplier The supplier to {@link Supplier#get()}.
* @return a result from the given Supplier.
* @since 3.18.0
*/
public <T> T get(final Supplier<T> supplier) {
startResume();
try {
return supplier.get();
} finally {
suspend();
}
}
/**
* Gets the Duration on this StopWatch.
*
* <p>
* This is either the Duration between the start and the moment this method is called, or the Duration between start and stop.
* </p>
*
* @return the Duration.
* @since 3.16.0
*/
public Duration getDuration() {
return Duration.ofNanos(getNanoTime());
}
/**
* Gets the message for string presentation.
*
* @return the message for string presentation.
* @since 3.10
*/
public String getMessage() {
return message;
}
/**
* Gets the split list.
*
* @return the list of splits.
* @since 3.20.0
*/
public List<Split> getSplits() {
return Collections.unmodifiableList(splits);
}
/**
* Gets the <em>elapsed</em> time in nanoseconds.
*
* <p>
* This is either the time between the start and the moment this method is called, or the amount of time between start and stop.
* </p>
*
* @return the <em>elapsed</em> time in nanoseconds.
* @see System#nanoTime()
* @since 3.0
*/
public long getNanoTime() {
switch (runningState) {
case STOPPED:
case SUSPENDED:
return stopTimeNanos - startTimeNanos;
case UNSTARTED:
return 0;
case RUNNING:
return System.nanoTime() - startTimeNanos;
default:
break;
}
throw new IllegalStateException("Illegal running state has occurred.");
}
/**
* Gets the split Duration on this StopWatch.
*
* <p>
* This is the Duration between start and latest split.
* </p>
*
* @return the split Duration.
* @throws IllegalStateException if this StopWatch has not yet been split.
* @since 3.16.0
*/
public Duration getSplitDuration() {
return Duration.ofNanos(getSplitNanoTime());
}
/**
* Gets the split time in nanoseconds.
*
* <p>
* This is the time between start and latest split.
* </p>
*
* @return the split time in nanoseconds.
* @throws IllegalStateException if this StopWatch has not yet been split.
* @since 3.0
*/
public long getSplitNanoTime() {
if (splitState != SplitState.SPLIT) {
throw new IllegalStateException("Stopwatch must be split to get the split time.");
}
return splits.get(splits.size() - 1).getRight().toNanos();
}
/**
* Gets the split time on this StopWatch.
*
* <p>
* This is the time between start and latest split.
* </p>
*
* @return the split time in milliseconds.
* @throws IllegalStateException if this StopWatch has not yet been split.
* @since 2.1
* @deprecated Use {@link #getSplitDuration()}.
*/
@Deprecated
public long getSplitTime() {
return nanosToMillis(getSplitNanoTime());
}
/**
* Gets the Instant this StopWatch was started, between the current time and midnight, January 1, 1970 UTC.
*
* @return the Instant this StopWatch was started, between the current time and midnight, January 1, 1970 UTC.
* @throws IllegalStateException if this StopWatch has not been started.
* @since 3.16.0
*/
public Instant getStartInstant() {
if (runningState == State.UNSTARTED) {
throw new IllegalStateException("Stopwatch has not been started");
}
return startInstant;
}
/**
* Gets the time this StopWatch was started in milliseconds, between the current time and midnight, January 1, 1970 UTC.
*
* @return the time this StopWatch was started in milliseconds, between the current time and midnight, January 1, 1970 UTC.
* @throws IllegalStateException if this StopWatch has not been started.
* @since 2.4
* @deprecated Use {@link #getStartInstant()}.
*/
@Deprecated
public long getStartTime() {
return getStartInstant().toEpochMilli();
}
/**
* Gets the Instant this StopWatch was stopped, between the current time and midnight, January 1, 1970 UTC.
*
* @return the Instant this StopWatch was stopped in milliseconds, between the current time and midnight, January 1, 1970 UTC.
* @throws IllegalStateException if this StopWatch has not been started.
* @since 3.16.0
*/
public Instant getStopInstant() {
if (runningState == State.UNSTARTED) {
throw new IllegalStateException("Stopwatch has not been started");
}
return stopInstant;
}
/**
* Gets the time this StopWatch was stopped in milliseconds, between the current time and midnight, January 1, 1970 UTC.
*
* @return the time this StopWatch was stopped in milliseconds, between the current time and midnight, January 1, 1970 UTC.
* @throws IllegalStateException if this StopWatch has not been started.
* @since 3.12.0
* @deprecated Use {@link #getStopInstant()}.
*/
@Deprecated
public long getStopTime() {
// stopTimeNanos stores System.nanoTime() for elapsed time
return getStopInstant().toEpochMilli();
}
/**
* Delegates to {@link FailableSupplier#get()} while recording the duration of the call.
*
* @param <T> the type of results supplied by this supplier.
* @param <E> The kind of thrown exception or error.
* @param supplier The supplier to {@link Supplier#get()}.
* @return a result from the given Supplier.
* @throws Throwable if the supplier fails.
* @since 3.18.0
*/
public <T, E extends Throwable> T getT(final FailableSupplier<T, E> supplier) throws Throwable {
startResume();
try {
return supplier.get();
} finally {
suspend();
}
}
/**
* Gets the time on this StopWatch.
*
* <p>
* This is either the time between the start and the moment this method is called, or the amount of time between start and stop.
* </p>
*
* @return the time in milliseconds.
* @see #getDuration()
*/
public long getTime() {
return nanosToMillis(getNanoTime());
}
/**
* Gets the time in the specified TimeUnit.
*
* <p>
* This is either the time between the start and the moment this method is called, or the amount of time between start and stop. The resulting time will be
* expressed in the desired TimeUnit with any remainder rounded down. For example, if the specified unit is {@code TimeUnit.HOURS} and this StopWatch time
* is 59 minutes, then the result returned will be {@code 0}.
* </p>
*
* @param timeUnit the unit of time, not null.
* @return the time in the specified TimeUnit, rounded down.
* @since 3.5
*/
public long getTime(final TimeUnit timeUnit) {
return timeUnit.convert(getNanoTime(), TimeUnit.NANOSECONDS);
}
/**
* Tests whether this StopWatch is started. A suspended StopWatch is also started watch.
*
* @return boolean If this StopWatch is started.
* @since 3.2
*/
public boolean isStarted() {
return runningState.isStarted();
}
/**
* Tests whether StopWatch is stopped. this StopWatch which's not yet started and explicitly stopped StopWatch is considered as stopped.
*
* @return boolean If this StopWatch is stopped.
* @since 3.2
*/
public boolean isStopped() {
return runningState.isStopped();
}
/**
* Tests whether this StopWatch is suspended.
*
* @return boolean If this StopWatch is suspended.
* @since 3.2
*/
public boolean isSuspended() {
return runningState.isSuspended();
}
/**
* Converts nanoseconds to milliseconds.
*
* @param nanos nanoseconds to convert.
* @return milliseconds conversion result.
*/
private long nanosToMillis(final long nanos) {
return nanos / NANO_2_MILLIS;
}
/**
* Resets this StopWatch. Stops it if need be.
*
* <p>
* This method clears the internal values to allow the object to be reused.
* </p>
*/
public void reset() {
runningState = State.UNSTARTED;
splitState = SplitState.UNSPLIT;
splits.clear();
}
/**
* Resumes this StopWatch after a suspend.
*
* <p>
* This method resumes the watch after it was suspended. The watch will not include time between the suspend and resume calls in the total time.
* </p>
*
* @throws IllegalStateException if this StopWatch has not been suspended.
*/
public void resume() {
if (runningState != State.SUSPENDED) {
throw new IllegalStateException("Stopwatch must be suspended to resume.");
}
startTimeNanos += System.nanoTime() - stopTimeNanos;
runningState = State.RUNNING;
}
/**
* Delegates to {@link Runnable#run()} while recording the duration of the call.
*
* @param runnable The runnable to {@link Runnable#run()}.
* @since 3.18.0
*/
public void run(final Runnable runnable) {
startResume();
try {
runnable.run();
} finally {
suspend();
}
}
/**
* Delegates to {@link FailableRunnable#run()} while recording the duration of the call.
*
* @param <E> The kind of {@link Throwable}.
* @param runnable The runnable to {@link FailableRunnable#run()}.
* @throws Throwable Thrown by {@link FailableRunnable#run()}.
* @since 3.18.0
*/
public <E extends Throwable> void runT(final FailableRunnable<E> runnable) throws Throwable {
startResume();
try {
runnable.run();
} finally {
suspend();
}
}
/**
* Splits the time.
*
* <p>
* This method sets the stop time of the watch to allow a time to be extracted. The start time is unaffected, enabling {@link #unsplit()} to continue the
* timing from the original start point.
* </p>
*
* @throws IllegalStateException if this StopWatch is not running.
*/
public void split() {
if (runningState != State.RUNNING) {
throw new IllegalStateException("Stopwatch is not running.");
}
stopTimeNanos = System.nanoTime();
splitState = SplitState.SPLIT;
splits.add(new Split(String.valueOf(splits.size()), Duration.ofNanos(stopTimeNanos - startTimeNanos)));
}
/**
* Splits the time with a label.
*
* <p>
* This method sets the stop time of the watch to allow a time to be extracted. The start time is unaffected, enabling {@link #unsplit()} to continue the
* timing from the original start point.
* </p>
*
* @param label A message for string presentation.
* @throws IllegalStateException if the StopWatch is not running.
* @since 3.20.0
*/
public void split(final String label) {
if (runningState != State.RUNNING) {
throw new IllegalStateException("Stopwatch is not running.");
}
stopTimeNanos = System.nanoTime();
splitState = SplitState.SPLIT;
splits.add(new Split(label, Duration.ofNanos(stopTimeNanos - startTimeNanos)));
}
/**
* Starts this StopWatch.
*
* <p>
* This method starts a new timing session, clearing any previous values.
* </p>
*
* @throws IllegalStateException if this StopWatch is already running.
*/
public void start() {
if (runningState == State.STOPPED) {
throw new IllegalStateException("Stopwatch must be reset before being restarted.");
}
if (runningState != State.UNSTARTED) {
throw new IllegalStateException("Stopwatch already started.");
}
startTimeNanos = System.nanoTime();
startInstant = Instant.now();
runningState = State.RUNNING;
splits.clear();
}
/**
* Starts or resumes this StopWatch.
*/
private void startResume() {
if (isStopped()) {
start();
} else if (isSuspended()) {
resume();
}
}
/**
* Stops this StopWatch.
*
* <p>
* This method ends a new timing session, allowing the time to be retrieved.
* </p>
*
* @throws IllegalStateException if this StopWatch is not running.
*/
public void stop() {
if (runningState != State.RUNNING && runningState != State.SUSPENDED) {
throw new IllegalStateException("Stopwatch is not running.");
}
if (runningState == State.RUNNING) {
stopTimeNanos = System.nanoTime();
stopInstant = Instant.now();
}
runningState = State.STOPPED;
}
/**
* Suspends this StopWatch for later resumption.
*
* <p>
* This method suspends the watch until it is resumed. The watch will not include time between the suspend and resume calls in the total time.
* </p>
*
* @throws IllegalStateException if this StopWatch is not currently running.
*/
public void suspend() {
if (runningState != State.RUNNING) {
throw new IllegalStateException("Stopwatch must be running to suspend.");
}
stopTimeNanos = System.nanoTime();
stopInstant = Instant.now();
runningState = State.SUSPENDED;
}
/**
* Gets a summary of the last split time that this StopWatch recorded as a string.
*
* <p>
* The format used is ISO 8601-like, [<em>message</em> ]<em>hours</em>:<em>minutes</em>:<em>seconds</em>.<em>milliseconds</em>.
* </p>
*
* @return the split time as a String.
* @since 2.1
* @since 3.10 Returns the prefix {@code "message "} if the message is set.
*/
public String toSplitString() {
final String msgStr = Objects.toString(message, StringUtils.EMPTY);
final String formattedTime = formatSplitTime();
return msgStr.isEmpty() ? formattedTime : msgStr + StringUtils.SPACE + formattedTime;
}
/**
* Gets a summary of the time that this StopWatch recorded as a string.
*
* <p>
* The format used is ISO 8601-like, [<em>message</em> ]<em>hours</em>:<em>minutes</em>:<em>seconds</em>.<em>milliseconds</em>.
* </p>
*
* @return the time as a String.
* @since 3.10 Returns the prefix {@code "message "} if the message is set.
*/
@Override
public String toString() {
final String msgStr = Objects.toString(message, StringUtils.EMPTY);
final String formattedTime = formatTime();
return msgStr.isEmpty() ? formattedTime : msgStr + StringUtils.SPACE + formattedTime;
}
/**
* Removes the split.
*
* <p>
* This method clears the stop time. The start time is unaffected, enabling timing from the original start point to continue.
* </p>
*
* @throws IllegalStateException if this StopWatch has not been split.
*/
public void unsplit() {
if (splitState != SplitState.SPLIT) {
throw new IllegalStateException("Stopwatch has not been split.");
}
splitState = SplitState.UNSPLIT;
splits.remove(splits.size() - 1);
}
/**
* Stores a split as a label and duration.
*
* @since 3.20.0
*/
public static final class Split extends ImmutablePair<String, Duration> {
/**
* Constructs a Split object with label and duration.
*
* @param label Label for this split.
* @param duration Duration for this split.
*/
public Split(String label, Duration duration) {
super(label, duration);
}
/**
* Gets the label of this split.
*
* @return The label of this split.
*/
public String getLabel() {
return getLeft();
}
/**
* Gets the duration of this split.
*
* @return The duration of this split..
*/
public Duration getDuration() {
return getRight();
}
/**
* Converts this instance to a string.
*
* @return this instance to a string.
*/
@Override
public String toString() {
return String.format("Split [%s, %s])", getLabel(), getDuration());
}
}
}