| 1 | @[has_globals] |
| 2 | module main |
| 3 | |
| 4 | import time |
| 5 | import v.debug |
| 6 | |
| 7 | __global counter = HookCounter{} |
| 8 | |
| 9 | struct HookCounter { |
| 10 | pub mut: |
| 11 | after int |
| 12 | before int |
| 13 | } |
| 14 | |
| 15 | @[heap] |
| 16 | struct Profiler { |
| 17 | mut: |
| 18 | fn_map map[string]time.StopWatch |
| 19 | } |
| 20 | |
| 21 | fn (mut p Profiler) trace_after(fn_name string) { |
| 22 | counter.after++ |
| 23 | println('>>> called after ${fn_name} - ${p.fn_map[fn_name].elapsed()}') |
| 24 | } |
| 25 | |
| 26 | fn (mut p Profiler) trace_before(fn_name string) { |
| 27 | p.fn_map[fn_name] = time.new_stopwatch() |
| 28 | println('>>> called before ${fn_name}') |
| 29 | counter.before++ |
| 30 | } |
| 31 | |
| 32 | fn test_call() { |
| 33 | println('${@FN} got called') |
| 34 | time.sleep(100) |
| 35 | } |
| 36 | |
| 37 | fn hook_before(fn_name string) { |
| 38 | counter.before++ |
| 39 | } |
| 40 | |
| 41 | fn hook_after(fn_name string) { |
| 42 | counter.after++ |
| 43 | } |
| 44 | |
| 45 | fn test_main() { |
| 46 | counter = HookCounter{} |
| 47 | mut myprofiler := Profiler{} |
| 48 | hook1 := debug.add_after_call(myprofiler.trace_after) |
| 49 | hook2 := debug.add_before_call(myprofiler.trace_before) |
| 50 | hook3 := debug.add_before_call(hook_before) |
| 51 | hook4 := debug.add_after_call(hook_after) |
| 52 | test_call() |
| 53 | debug.remove_after_call(hook1) |
| 54 | debug.remove_before_call(hook2) |
| 55 | debug.remove_before_call(hook3) |
| 56 | debug.remove_after_call(hook4) |
| 57 | test_call() |
| 58 | $if trace ? { |
| 59 | assert counter.before == 4 |
| 60 | assert counter.after == 4 |
| 61 | } $else { |
| 62 | assert counter.before == 0 |
| 63 | assert counter.after == 0 |
| 64 | } |
| 65 | } |
| 66 | |