v2 / vlib / v / tests / bench / bench_gc_enable_disable_collect.v
44 lines · 40 sloc · 1.4 KB · a373bee98b978ed31f1bee757769ee3245e7adb0
Raw
1// The goal of this program, is to test V's garbage collector interaction with gc_disable(), gc_enable(), gc_collect() and `-gc none`.
2// Note that this program is intended to be run on Linux, where /proc/PID/status exists.
3// It should run on other platforms too, but the last columns of the output will be empty.
4// Example invocation: `MAX_ITERATIONS=100 BLOCK_SIZE=1_000_000 v run gc.v` .
5import os
6
7const block_size = os.getenv_opt('BLOCK_SIZE') or { '1_000' }.int()
8const max_iterations = os.getenv_opt('MAX_ITERATIONS') or { '40' }.int()
9
10fn do_some_work_and_allocate_memory() u64 {
11 a := []u8{len: block_size, init: u8(index)}
12 mut s := u64(0)
13 for x in a {
14 s += x
15 }
16 return s
17}
18
19fn process_mem_stats(pid int) string {
20 lines := os.read_lines('/proc/${pid}/status') or { [] }
21 mut vals := map[string]string{}
22 for line in lines {
23 x := line.split(':')
24 vals[x[0]] = x[1]
25 }
26 return 'VmSize: ${vals['VmSize']} | VmRSS: ${vals['VmRSS']}'
27}
28
29fn main() {
30 println('BLOCK_SIZE: ${block_size:15}, MAX_ITERATIONS: ${max_iterations:5}, gc_is_enabled: ${gc_is_enabled()}')
31 gc_disable()
32 mypid := os.getpid()
33 for c := 0; c < max_iterations; c++ {
34 if c % 15 == 0 {
35 gc_enable()
36 }
37 gc_collect()
38 s := do_some_work_and_allocate_memory()
39 println('gc_is_enabled: ${gc_is_enabled():6}, c: ${c:5}, s: ${s:10}, gc_memory_use: ${gc_memory_use():10}, ${process_mem_stats(mypid):30}')
40 if c % 15 == 0 {
41 gc_disable()
42 }
43 }
44}
45