-
Notifications
You must be signed in to change notification settings - Fork 0
/
stopwatch.go
51 lines (44 loc) · 782 Bytes
/
stopwatch.go
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
package main
import "time"
type stopwatch struct {
elapsed time.Duration
lastElapsed time.Duration
start time.Time
lastStart time.Time
isRunning bool
}
func (s *stopwatch) Start() {
if !s.isRunning {
s.start = time.Now()
s.lastStart = s.start
s.isRunning = true
}
}
func (s *stopwatch) Stop() {
if s.isRunning {
s.lastElapsed = time.Since(s.lastStart)
s.elapsed += time.Since(s.start)
s.isRunning = false
}
}
func (s *stopwatch) Flip() {
if s.isRunning {
s.Stop()
} else {
s.Start()
}
}
func (s *stopwatch) Elapsed() time.Duration {
if s.isRunning {
s.elapsed += time.Since(s.start)
s.start = time.Now()
}
return s.elapsed
}
func newStopwatch(start bool) stopwatch {
var sw stopwatch
if start {
sw.Start()
}
return sw
}