v2 / vlib / v / tests / bench / bench_rand_fill_buffer_from_set.v
54 lines · 49 sloc · 1.7 KB · a1c6377ab688e4ce40956675c27ef12247d04721
Raw
1import os
2import rand
3import time
4import rand.pcg32
5
6const buf_len = os.getenv_opt('BUF_LEN') or { '100_000_000' }.int()
7const nthreads = os.getenv_opt('VJOBS') or { '2' }.int()
8const max_iterations = os.getenv_opt('MAX_ITERATIONS') or { '4' }.int()
9
10fn main() {
11 mut buf := []u8{len: buf_len}
12 mut arr := []thread{}
13 sw := time.new_stopwatch()
14 for i in 0 .. nthreads {
15 part_len := buf.len / nthreads
16 start := i * part_len
17 mut chunk := &WorkChunk{
18 thread_id: i
19 // make the last thread fill the remaining characters too:
20 part: unsafe { buf[start..if i == nthreads - 1 { buf.len } else { start + part_len }] }
21 }
22 arr << spawn worker(mut chunk)
23 }
24 arr.wait()
25 elapsed := sw.elapsed().milliseconds()
26 mut histogram := []u64{len: 58}
27 for b in buf {
28 histogram[b]++
29 }
30 println(' buf: ${buf#[..10]} ... ${buf#[-10..]}')
31 println(' histogram: ${histogram#[48..]}')
32 println('Total took ${elapsed:6}ms, VJOBS: ${nthreads:2}, MAX_ITERATIONS: ${max_iterations:5}, BUF_LEN: ${buf_len:6}')
33 println('')
34}
35
36struct WorkChunk {
37 thread_id int
38mut:
39 part []u8
40}
41
42const charset = '0123456789'
43
44fn worker(mut chunk WorkChunk) {
45 mut rng := rand.PRNG(pcg32.PCG32RNG{})
46 sw := time.new_stopwatch()
47 for _ in 0 .. max_iterations {
48 rng.fill_buffer_from_set(charset, mut chunk.part)
49 }
50 elapsed_time_ns := sw.elapsed().nanoseconds()
51 fill_ms := u64(f64(elapsed_time_ns) / f64(max_iterations * 1_000_000))
52 rand_character_ns := f64(elapsed_time_ns) / f64(max_iterations * chunk.part.len)
53 println(' thread ${chunk.thread_id:2}, took ${elapsed_time_ns / 1_000_000:6}ms, per fill: ${fill_ms:6}ms, per character: ${rand_character_ns:5.0}ns, part: ${chunk.part#[..3]}...${chunk.part#[-3..]}, part.len: ${chunk.part.len:6}')
54}
55