Class: RequireProfiler::Printer::JSON

Inherits:
CallStack show all
Defined in:
lib/require_profiler/printer/json.rb

Overview

JSON formatter converts call tacks into Speedscope compatible JSON on finish.

Can only be used with rewindable IO.

Instance Method Summary collapse

Methods inherited from CallStack

#flush

Methods inherited from Base

#flush, #initialize

Constructor Details

This class inherits a constructor from RequireProfiler::Printer::Base

Instance Method Details

#finishObject



12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
# File 'lib/require_profiler/printer/json.rb', line 12

def finish
  output.rewind
  stacks = output.read
  output.rewind

  frames = []
  frame_index = {}

  samples = []
  weights = []

  stacks.each_line do |line|
    line = line.strip
    next if line.empty?

    sep = line.rindex(" ")
    next unless sep

    stack = line[0...sep]
    weight = line[(sep + 1)..].to_f

    sample = stack.split(";").map do |name|
      frame_index[name] ||= begin
        frames << {name: name}
        frames.size - 1
      end
    end

    samples << sample
    weights << weight
  end

  total = weights.sum

  profile = {
    "$schema" => "https://www.speedscope.app/file-format-schema.json",
    :shared => {frames: frames},
    :profiles => [
      {
        type: "sampled",
        unit: "milliseconds",
        startValue: 0,
        endValue: total,
        samples:,
        weights:
      }
    ]
  }

  output.write(::JSON.pretty_generate(profile))
  super
end