Sha256: c97c01dce38cf324833667d4f581b161fd444b5558bc599052a6569a6a5a15ec

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

# frozen_string_literal: true

# STD Libs
require 'benchmark'

# This Gem
require 'require_bench/version'

module RequireBench
  TIMINGS = Hash.new { |h, k| h[k] = 0.0 }
  skips = ENV['REQUIRE_BENCH_SKIP_PATTERN']
  if skips
    skip_pattern = case skips
                   when /,/ then
                     Regexp.union(*skips.split(','))
                   when /\|/ then
                     Regexp.union(*skips.split('|'))
                   end
    puts "[RequireBench] Setting REQUIRE_BENCH_SKIP_PATTERN to #{skip_pattern}"
  end
  SKIP_PATTERN = skips

  if ENV['REQUIRE_BENCH'] == 'true'
    def require_with_timing(file)
      $require_bench_semaphore = true
      ret = nil
      seconds = Benchmark.realtime { ret = Kernel.send(:require_without_timing, file) }
      printf("[RequireBench] %10f %s\n", seconds, file)
      path_parts = file.split('/')
      prefix = path_parts.first
      # requires that were fully qualified paths probably need to be identified
      #   by the full path
      prefix = file if prefix.nil? || prefix.empty?
      RequireBench::TIMINGS[prefix] += seconds
      ret
    ensure
      $require_bench_semaphore = nil
    end
    module_function :require_with_timing
  end
end

if ENV['REQUIRE_BENCH'] == 'true'
  # A Kernel hack that adds require timing to find require problems in app.
  module Kernel
    alias require_without_timing require

    def require(file)
      file = file.to_s

      # Global $ variable, which is always truthy while inside the hack, is to
      #   prevent a scenario that might result in infinite recursion.
      return require_without_timing(file) if $require_bench_semaphore
      if RequireBench::SKIP_PATTERN && file =~ RequireBench::SKIP_PATTERN
        return require_without_timing(file)
      end

      RequireBench.require_with_timing(file)
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
require_bench-1.0.2 lib/require_bench.rb