Sha256: be6d8eb31497ecb6e6795d8a9c5ab0259a2c5de2523c6c109db153e0195aa58b

Contents?: true

Size: 1.46 KB

Versions: 2

Compression:

Stored size: 1.46 KB

Contents

# frozen_string_literal: true

# (c) Copyright 2020 Ribose Inc.
#

module IEV
  class Profiler
    attr_reader :bench, :dir, :prefix, :profile

    def self.measure(prefix = nil, &block)
      new(prefix).run(&block)
    end

    def initialize(prefix, dir: "profile")
      @prefix = prefix
      @dir = dir
    end

    def run(&block)
      profiler_enabled? ? run!(&block) : block.call
    end

    def run!(&block)
      retval = nil
      @profile = RubyProf.profile allow_exceptions: true do
        @bench = Benchmark.measure do
          retval = block.call
        end
      end
      retval
    ensure
      print_reports
    end

    def profiler_enabled?
      $IEV_PROFILE
    end

    private

    def print_reports
      FileUtils.mkdir_p(dir)
      print_benchmark("bench.txt")
      print_profile("flat.txt", RubyProf::FlatPrinter)
      print_profile("graph.html", RubyProf::GraphHtmlPrinter)
      print_profile("calls.html", RubyProf::CallStackPrinter)
    end

    def print_benchmark(suffix)
      return if bench.nil?

      contents = [Benchmark::CAPTION, bench.to_s].join("\n")
      File.write(report_file_name(suffix), contents)
    end

    def print_profile(suffix, printer)
      return if profile.nil?

      File.open(report_file_name(suffix), "w") do |file|
        printer.new(profile).print(file)
      end
    end

    def report_file_name(suffix)
      base_name = [prefix, suffix].compact.join("-")
      File.expand_path(base_name, dir)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
iev-0.3.4 lib/iev/profiler.rb
iev-0.3.3 lib/iev/profiler.rb