Class: EmergeCLI::Profiler
- Inherits:
-
Object
- Object
- EmergeCLI::Profiler
- Defined in:
- lib/utils/profiler.rb
Overview
NOTE: This class is not thread-safe.
Instance Method Summary collapse
-
#initialize(enabled: false) ⇒ Profiler
constructor
A new instance of Profiler.
- #measure(label) ⇒ Object
- #report ⇒ Object
- #start(label) ⇒ Object
- #stop(label) ⇒ Object
Constructor Details
#initialize(enabled: false) ⇒ Profiler
Returns a new instance of Profiler.
4 5 6 7 8 |
# File 'lib/utils/profiler.rb', line 4 def initialize(enabled: false) @enabled = enabled @measurements = {} @start_times = {} end |
Instance Method Details
#measure(label) ⇒ Object
10 11 12 13 14 15 16 17 |
# File 'lib/utils/profiler.rb', line 10 def measure(label) return yield unless @enabled start(label) result = yield stop(label) result end |
#report ⇒ Object
34 35 36 37 38 39 40 41 42 43 44 45 46 47 |
# File 'lib/utils/profiler.rb', line 34 def report return unless @enabled Logger.info '=== Performance Profile ===' @measurements.sort_by { |_, v| -v[:total_time] }.each do |label, data| avg_time = data[:total_time] / data[:count] Logger.info sprintf('%-<label>30s Total: %<total>.2fs Count: %<count>d Avg: %<avg>.2fs', label: label, total: data[:total_time], count: data[:count], avg: avg_time) end Logger.info '==========================' end |
#start(label) ⇒ Object
19 20 21 22 |
# File 'lib/utils/profiler.rb', line 19 def start(label) return unless @enabled @start_times[label] = Time.now end |
#stop(label) ⇒ Object
24 25 26 27 28 29 30 31 32 |
# File 'lib/utils/profiler.rb', line 24 def stop(label) return unless @enabled return unless @start_times[label] duration = Time.now - @start_times[label] @measurements[label] ||= { count: 0, total_time: 0 } @measurements[label][:count] += 1 @measurements[label][:total_time] += duration end |