v

Зеркало из https://github.com/vlang/v
Форк
0
/
stopwatch.v 
74 строки · 1.6 Кб
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.
4
module time
5

6
@[params]
7
pub struct StopWatchOptions {
8
pub:
9
	auto_start bool = true
10
}
11

12
// StopWatch is used to measure elapsed time.
13
pub struct StopWatch {
14
mut:
15
	elapsed u64
16
pub mut:
17
	start u64
18
	end   u64
19
}
20

21
// new_stopwatch initializes a new StopWatch with the current time as start.
22
pub fn new_stopwatch(opts StopWatchOptions) StopWatch {
23
	mut initial := u64(0)
24
	if opts.auto_start {
25
		initial = sys_mono_now()
26
	}
27
	return StopWatch{
28
		elapsed: 0
29
		start:   initial
30
		end:     0
31
	}
32
}
33

34
// start starts the stopwatch. If the timer was paused, it continues counting.
35
pub fn (mut t StopWatch) start() {
36
	t.start = sys_mono_now()
37
	t.end = 0
38
}
39

40
// restart restarts the stopwatch. If the timer was paused, it restarts counting.
41
pub fn (mut t StopWatch) restart() {
42
	t.start = sys_mono_now()
43
	t.end = 0
44
	t.elapsed = 0
45
}
46

47
// stop stops the timer, by setting the end time to the current time.
48
pub fn (mut t StopWatch) stop() {
49
	t.end = sys_mono_now()
50
}
51

52
// pause resets the `start` time and adds the current elapsed time to `elapsed`.
53
pub fn (mut t StopWatch) pause() {
54
	if t.start > 0 {
55
		if t.end == 0 {
56
			t.elapsed += sys_mono_now() - t.start
57
		} else {
58
			t.elapsed += t.end - t.start
59
		}
60
	}
61
	t.start = 0
62
}
63

64
// elapsed returns the Duration since the last start call
65
pub fn (t StopWatch) elapsed() Duration {
66
	if t.start > 0 {
67
		if t.end == 0 {
68
			return Duration(i64(sys_mono_now() - t.start + t.elapsed))
69
		} else {
70
			return Duration(i64(t.end - t.start + t.elapsed))
71
		}
72
	}
73
	return Duration(i64(t.elapsed))
74
}
75

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.