1
0
mirror of https://github.com/vlang/v.git synced 2023-08-10 21:13:21 +03:00
v/vlib/time/stopwatch.v

74 lines
1.6 KiB
V
Raw Permalink Normal View History

2023-03-28 23:55:57 +03:00
// Copyright (c) 2019-2023 Alexander Medvednikov. All rights reserved.
// Use of this source code is governed by an MIT license
// that can be found in the LICENSE file.
module time
[params]
pub struct StopWatchOptions {
auto_start bool = true
}
2021-01-13 17:30:54 +03:00
// StopWatch is used to measure elapsed time.
pub struct StopWatch {
mut:
elapsed u64
pub mut:
start u64
end u64
}
2021-01-13 17:30:54 +03:00
// new_stopwatch initializes a new StopWatch with the current time as start.
pub fn new_stopwatch(opts StopWatchOptions) StopWatch {
mut initial := u64(0)
if opts.auto_start {
2020-12-06 17:19:39 +03:00
initial = sys_mono_now()
}
return StopWatch{
elapsed: 0
start: initial
end: 0
}
}
2023-07-22 21:30:36 +03:00
// start starts the stopwatch. If the timer was paused, it continues counting.
2020-05-17 14:51:18 +03:00
pub fn (mut t StopWatch) start() {
2020-12-06 17:19:39 +03:00
t.start = sys_mono_now()
t.end = 0
}
2023-07-22 21:30:36 +03:00
// restart restarts the stopwatch. If the timer was paused, it restarts counting.
2020-05-17 14:51:18 +03:00
pub fn (mut t StopWatch) restart() {
2020-12-06 17:19:39 +03:00
t.start = sys_mono_now()
t.end = 0
t.elapsed = 0
}
2021-01-13 17:30:54 +03:00
// stop stops the timer, by setting the end time to the current time.
2020-05-17 14:51:18 +03:00
pub fn (mut t StopWatch) stop() {
2020-12-06 17:19:39 +03:00
t.end = sys_mono_now()
}
2021-01-13 17:30:54 +03:00
// pause resets the `start` time and adds the current elapsed time to `elapsed`.
2020-05-17 14:51:18 +03:00
pub fn (mut t StopWatch) pause() {
if t.start > 0 {
if t.end == 0 {
2020-12-06 17:19:39 +03:00
t.elapsed += sys_mono_now() - t.start
} else {
t.elapsed += t.end - t.start
}
}
t.start = 0
}
// elapsed returns the Duration since the last start call
pub fn (t StopWatch) elapsed() Duration {
if t.start > 0 {
if t.end == 0 {
2020-12-06 17:19:39 +03:00
return Duration(i64(sys_mono_now() - t.start + t.elapsed))
} else {
return Duration(i64(t.end - t.start + t.elapsed))
}
}
return Duration(i64(t.elapsed))
}