| 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` . |
| 5 | import os |
| 6 | |
| 7 | const block_size = os.getenv_opt('BLOCK_SIZE') or { '1_000' }.int() |
| 8 | const max_iterations = os.getenv_opt('MAX_ITERATIONS') or { '40' }.int() |
| 9 | |
| 10 | fn 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 | |
| 19 | fn 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 | |
| 29 | fn 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 | |