|
| 1 | +# frozen_string_literal: true |
| 2 | + |
| 3 | +require_relative '../misc/stats' |
| 4 | +require 'json' |
| 5 | +begin |
| 6 | + require 'gruff' |
| 7 | +rescue LoadError |
| 8 | + Gem.install('gruff') |
| 9 | + gem 'gruff' |
| 10 | + require 'gruff' |
| 11 | +end |
| 12 | + |
| 13 | +# Renders benchmark data as a graph |
| 14 | +class GraphRenderer |
| 15 | + DEFAULT_WIDTH = 1600 |
| 16 | + COLOR_PALETTE = %w[#3285e1 #489d32 #e2c13e #8A6EAF #D1695E].freeze |
| 17 | + THEME = { |
| 18 | + colors: COLOR_PALETTE, |
| 19 | + marker_color: '#dddddd', |
| 20 | + font_color: 'black', |
| 21 | + background_colors: 'white' |
| 22 | + }.freeze |
| 23 | + DEFAULT_BOTTOM_MARGIN = 30.0 |
| 24 | + DEFAULT_LEGEND_MARGIN = 4.0 |
| 25 | + |
| 26 | + class << self |
| 27 | + def render(json_path, png_path, title_font_size: 16.0, legend_font_size: 12.0, marker_font_size: 10.0) |
| 28 | + ruby_descriptions, data, baseline, bench_names = load_benchmark_data(json_path) |
| 29 | + |
| 30 | + graph = Gruff::Bar.new(DEFAULT_WIDTH) |
| 31 | + configure_graph(graph, ruby_descriptions, bench_names, title_font_size, legend_font_size, marker_font_size) |
| 32 | + |
| 33 | + ruby_descriptions.each do |ruby, description| |
| 34 | + speedups = calculate_speedups(data, baseline, ruby, bench_names) |
| 35 | + graph.data "#{ruby}: #{description}", speedups |
| 36 | + end |
| 37 | + graph.write(png_path) |
| 38 | + png_path |
| 39 | + end |
| 40 | + |
| 41 | + private |
| 42 | + |
| 43 | + def load_benchmark_data(json_path) |
| 44 | + json = JSON.load_file(json_path) |
| 45 | + ruby_descriptions = json.fetch("metadata") |
| 46 | + data = json.fetch("raw_data") |
| 47 | + baseline = ruby_descriptions.first.first |
| 48 | + bench_names = data.first.last.keys |
| 49 | + |
| 50 | + [ruby_descriptions, data, baseline, bench_names] |
| 51 | + end |
| 52 | + |
| 53 | + def configure_graph(graph, ruby_descriptions, bench_names, title_font_size, legend_font_size, marker_font_size) |
| 54 | + graph.title = "Speedup ratio relative to #{ruby_descriptions.keys.first}" |
| 55 | + graph.title_font_size = title_font_size |
| 56 | + graph.theme = THEME |
| 57 | + graph.labels = bench_names.map.with_index { |bench, index| [index, bench] }.to_h |
| 58 | + graph.show_labels_for_bar_values = true |
| 59 | + graph.bottom_margin = DEFAULT_BOTTOM_MARGIN |
| 60 | + graph.legend_margin = DEFAULT_LEGEND_MARGIN |
| 61 | + graph.legend_font_size = legend_font_size |
| 62 | + graph.marker_font_size = marker_font_size |
| 63 | + end |
| 64 | + |
| 65 | + def calculate_speedups(data, baseline, ruby, bench_names) |
| 66 | + bench_names.map { |bench| |
| 67 | + baseline_times = data.fetch(baseline).fetch(bench).fetch("bench") |
| 68 | + times = data.fetch(ruby).fetch(bench).fetch("bench") |
| 69 | + Stats.new(baseline_times).mean / Stats.new(times).mean |
| 70 | + } |
| 71 | + end |
| 72 | + end |
| 73 | +end |
0 commit comments