Module: Utils::Profiling Private

Defined in:
utils/profiling.rb

This module is part of a private API. This module may only be used in the Homebrew/brew repository. Third parties should avoid using this module if possible, as it may be removed or changed without warning.

Class Method Summary collapse

Class Method Details

.inject_stats!(the_module, pattern) ⇒ Object

This method is part of a private API. This method may only be used in the Homebrew/brew repository. Third parties should avoid using this method if possible, as it may be removed or changed without warning.



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
36
37
38
39
40
41
42
43
# File 'utils/profiling.rb', line 11

def self.inject_stats!(the_module, pattern)
  @injected_modules[the_module] ||= []
  injected_methods = @injected_modules.fetch(the_module)
  wrapper = Module.new
  the_module.instance_methods.grep(pattern).each do |name|
    next if injected_methods.include? name

    injected_methods << name
    wrapper.define_method(name) do |*args, &block|
      require "time"

      time = Time.now

      begin
        super(*args, &block)
      ensure
        $times[name] ||= 0
        $times[name] += Time.now - time
      end
    end
  end
  the_module.prepend(wrapper)

  return unless $times.nil?

  $times = {}
  Kernel.at_exit do
    col_width = [$times.keys.map(&:size).max.to_i + 2, 15].max
    $times.sort_by { |_method, time| time }.each do |method, time|
      $stdout.puts Kernel.format("%<method>-#{col_width}s %<time>0.4f sec", method: "#{method}:", time:)
    end
  end
end