Class: Ree::BenchmarkTracer

Inherits:
Object show all
Defined in:
lib/ree/benchmark_tracer.rb

Defined Under Namespace

Classes: Node

Constant Summary collapse

THREAD_KEY =
:ree_benchmark_tracer

Class Method Summary collapse

Class Method Details

.active?Boolean

Returns:

  • (Boolean)


37
38
39
40
# File 'lib/ree/benchmark_tracer.rb', line 37

def active?
  stack = Thread.current[THREAD_KEY]
  stack && !stack.empty?
end

.collect(name) ⇒ Object

Collector trace — only participates if a trace is already active



43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/ree/benchmark_tracer.rb', line 43

def collect(name)
  stack = Thread.current[THREAD_KEY]
  return yield unless stack && !stack.empty?

  node = Node.new(name, Process.clock_gettime(Process::CLOCK_MONOTONIC), nil, [])
  stack.last.children.push(node)
  stack.push(node)

  begin
    result = yield
  ensure
    node.duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - node.start_time
    stack.pop
  end

  result
end

.format_tree(node, deep: true, hide_ree_lib: true) ⇒ Object

Format tree as a string deep: false → only root node, deep: true → full tree



63
64
65
66
67
# File 'lib/ree/benchmark_tracer.rb', line 63

def format_tree(node, deep: true, hide_ree_lib: true)
  lines = []
  build_tree_lines(node, 0, lines, deep: deep, hide_ree_lib: hide_ree_lib)
  lines.join("\n")
end

.trace(name, output_proc: nil, deep: true, hide_ree_lib: true) ⇒ Object

Entry point trace — starts collection, outputs when root completes



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/ree/benchmark_tracer.rb', line 10

def trace(name, output_proc: nil, deep: true, hide_ree_lib: true)
  stack = Thread.current[THREAD_KEY] ||= []
  node = Node.new(name, Process.clock_gettime(Process::CLOCK_MONOTONIC), nil, [])
  stack.last.children.push(node) if stack.last
  is_root = stack.empty? || stack.last.nil?
  stack.push(node)

  begin
    result = yield
  ensure
    node.duration = Process.clock_gettime(Process::CLOCK_MONOTONIC) - node.start_time
    stack.pop

    if stack.empty?
      Thread.current[THREAD_KEY] = nil

      if output_proc
        output_proc.call(format_tree(node, deep: deep, hide_ree_lib: hide_ree_lib))
      else
        $stdout.puts(format_tree(node, deep: deep, hide_ree_lib: hide_ree_lib))
      end
    end
  end

  result
end