v / vlib / time / stopwatch_test.v
36 lines · 33 sloc · 1.32 KB · 19f080ffb8f8f01976692f6b79d9f857c685e109
Raw
1import time
2
3// Note: on CI jobs, especially msvc ones, sleep_ms may sleep for much more
4// time than you have specified. To avoid false positives from CI test
5// failures, some of the asserts will be run only if you pass `-d stopwatch`
6fn test_stopwatch_works_as_intended() {
7 mut sw := time.new_stopwatch()
8 // sample code that you want to measure:
9 println('Hello world')
10 time.sleep(1 * time.millisecond)
11
12 println('Greeting the world took: ${sw.elapsed().nanoseconds()}ns')
13 assert sw.elapsed().nanoseconds() > 0
14}
15
16fn test_stopwatch_time_between_pause_and_start_should_be_skipped_in_elapsed() {
17 println('Testing pause function')
18 mut sw := time.new_stopwatch()
19 time.sleep(10 * time.millisecond) // A
20 eprintln('Elapsed after 10ms nap: ${sw.elapsed().milliseconds()}ms')
21 assert sw.elapsed().milliseconds() >= 8 // sometimes it sleeps for 9ms on windows..
22 sw.pause()
23 time.sleep(10 * time.millisecond)
24 eprintln('Elapsed after pause and another 10ms nap: ${sw.elapsed().milliseconds()}ms')
25 assert sw.elapsed().milliseconds() >= 8
26 $if stopwatch ? {
27 assert sw.elapsed().milliseconds() < 20
28 }
29 sw.start()
30 time.sleep(10 * time.millisecond) // B
31 eprintln('Elapsed after resume and another 10ms nap: ${sw.elapsed().milliseconds()}ms')
32 assert sw.elapsed().milliseconds() >= 18
33 $if stopwatch ? {
34 assert sw.elapsed().milliseconds() < 30
35 }
36}
37