v / vlib / time / stopwatch.v
79 lines · 71 sloc · 1.73 KB · a01af79d05c4487ccca28f26ba6b265c04fc796c
Raw
1// Copyright (c) 2019-2024 Alexander Medvednikov. All rights reserved.
2// Use of this source code is governed by an MIT license
3// that can be found in the LICENSE file.
4module time
5
6@[params]
7pub struct StopWatchOptions {
8pub:
9 auto_start bool = true
10}
11
12// StopWatch is used to measure elapsed time.
13pub struct StopWatch {
14mut:
15 elapsed u64
16 started bool
17pub mut:
18 start u64
19 end u64
20}
21
22// new_stopwatch initializes a new StopWatch with the current time as start.
23pub fn new_stopwatch(opts StopWatchOptions) StopWatch {
24 mut initial := u64(0)
25 if opts.auto_start {
26 initial = sys_mono_now()
27 }
28 return StopWatch{
29 elapsed: 0
30 started: opts.auto_start
31 start: initial
32 end: 0
33 }
34}
35
36// start starts the stopwatch. If the timer was paused, it continues counting.
37pub fn (mut t StopWatch) start() {
38 t.start = sys_mono_now()
39 t.end = 0
40 t.started = true
41}
42
43// restart restarts the stopwatch. If the timer was paused, it restarts counting.
44pub fn (mut t StopWatch) restart() {
45 t.start = sys_mono_now()
46 t.end = 0
47 t.elapsed = 0
48 t.started = true
49}
50
51// stop stops the timer, by setting the end time to the current time.
52pub fn (mut t StopWatch) stop() {
53 t.end = sys_mono_now()
54}
55
56// pause resets the `start` time and adds the current elapsed time to `elapsed`.
57pub fn (mut t StopWatch) pause() {
58 if t.started {
59 if t.end == 0 {
60 t.elapsed += sys_mono_now() - t.start
61 } else {
62 t.elapsed += t.end - t.start
63 }
64 }
65 t.start = 0
66 t.started = false
67}
68
69// elapsed returns the Duration since the last start call.
70pub fn (t StopWatch) elapsed() Duration {
71 if t.started {
72 if t.end == 0 {
73 return Duration(i64(sys_mono_now() - t.start + t.elapsed))
74 } else {
75 return Duration(i64(t.end - t.start + t.elapsed))
76 }
77 }
78 return Duration(i64(t.elapsed))
79}
80