v
Зеркало из https://github.com/vlang/v
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:
9auto_start bool = true
10}
11
12// StopWatch is used to measure elapsed time.
13pub struct StopWatch {
14mut:
15elapsed u64
16pub mut:
17start u64
18end u64
19}
20
21// new_stopwatch initializes a new StopWatch with the current time as start.
22pub fn new_stopwatch(opts StopWatchOptions) StopWatch {
23mut initial := u64(0)
24if opts.auto_start {
25initial = sys_mono_now()
26}
27return StopWatch{
28elapsed: 0
29start: initial
30end: 0
31}
32}
33
34// start starts the stopwatch. If the timer was paused, it continues counting.
35pub fn (mut t StopWatch) start() {
36t.start = sys_mono_now()
37t.end = 0
38}
39
40// restart restarts the stopwatch. If the timer was paused, it restarts counting.
41pub fn (mut t StopWatch) restart() {
42t.start = sys_mono_now()
43t.end = 0
44t.elapsed = 0
45}
46
47// stop stops the timer, by setting the end time to the current time.
48pub fn (mut t StopWatch) stop() {
49t.end = sys_mono_now()
50}
51
52// pause resets the `start` time and adds the current elapsed time to `elapsed`.
53pub fn (mut t StopWatch) pause() {
54if t.start > 0 {
55if t.end == 0 {
56t.elapsed += sys_mono_now() - t.start
57} else {
58t.elapsed += t.end - t.start
59}
60}
61t.start = 0
62}
63
64// elapsed returns the Duration since the last start call
65pub fn (t StopWatch) elapsed() Duration {
66if t.start > 0 {
67if t.end == 0 {
68return Duration(i64(sys_mono_now() - t.start + t.elapsed))
69} else {
70return Duration(i64(t.end - t.start + t.elapsed))
71}
72}
73return Duration(i64(t.elapsed))
74}
75