-
Notifications
You must be signed in to change notification settings - Fork 157
/
Copy pathStopWatch.scala
70 lines (58 loc) · 1.63 KB
/
StopWatch.scala
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
/*
* Copyright (c) 2021-2022 Jarek Sacha. All Rights Reserved.
*
* Author's e-mail: jpsacha at gmail.com
*/
package opencv_cookbook
import java.util.concurrent.TimeUnit
import scala.concurrent.duration.Duration
/**
* StopWatch that can track of repeated start/stop intervals.
*/
class StopWatch {
private var accumulatedDuration = Duration.Zero
private var startTime: Option[Long] = None
private var stopCount: Long = 0L
def start(): Unit = {
startTime = Option(System.nanoTime())
}
def stop(): Unit = {
startTime match {
case Some(t0) =>
accumulatedDuration = accumulatedDuration + Duration(System.nanoTime() - t0, TimeUnit.NANOSECONDS)
startTime = None
stopCount += 1
case None =>
throw new IllegalStateException("StopWatch: cannot stop, not started.")
}
}
def reset(): Unit = {
accumulatedDuration = Duration.Zero
startTime = None
stopCount = 0
}
def add[R](op: => R): R = {
start()
val r = op
stop()
r
}
def duration: Duration = {
startTime match {
case Some(t0) =>
accumulatedDuration + Duration(System.nanoTime() - t0, TimeUnit.NANOSECONDS)
case None =>
accumulatedDuration
}
}
def durationMillis: Double = duration.toUnit(TimeUnit.MILLISECONDS)
def durationMicros: Double = duration.toUnit(TimeUnit.MICROSECONDS)
def averageDuration: Duration = {
if (startTime.isEmpty) {
if (stopCount == 0) Duration.Zero else duration / stopCount.toDouble
} else {
throw new IllegalStateException("Cannot average when in stated state.")
}
}
def intervalCount: Long = stopCount
}