Class: TRuby::CompilationProfiler

Inherits:
Object
  • Object
show all
Defined in:
lib/t_ruby/cache.rb

Overview

Compilation profiler

Instance Method Summary collapse

Constructor Details

#initializeCompilationProfiler

Returns a new instance of CompilationProfiler.



730
731
732
733
# File 'lib/t_ruby/cache.rb', line 730

def initialize
  @timings = {}
  @call_counts = {}
end

Instance Method Details

#profile(name, &block) ⇒ Object



735
736
737
738
739
740
741
742
743
744
745
746
747
# File 'lib/t_ruby/cache.rb', line 735

def profile(name, &block)
  start = Process.clock_gettime(Process::CLOCK_MONOTONIC)
  result = block.call
  elapsed = Process.clock_gettime(Process::CLOCK_MONOTONIC) - start

  @timings[name] ||= 0.0
  @timings[name] += elapsed

  @call_counts[name] ||= 0
  @call_counts[name] += 1

  result
end

#reportObject



749
750
751
752
753
754
755
756
# File 'lib/t_ruby/cache.rb', line 749

def report
  puts "=== Compilation Profile ==="
  @timings.sort_by { |_, v| -v }.each do |name, time|
    calls = @call_counts[name]
    avg = time / calls
    puts "#{name}: #{format('%.3f', time)}s total, #{calls} calls, #{format('%.3f', avg * 1000)}ms avg"
  end
end

#resetObject



758
759
760
761
# File 'lib/t_ruby/cache.rb', line 758

def reset
  @timings.clear
  @call_counts.clear
end

#to_hObject



763
764
765
766
767
768
769
770
771
772
# File 'lib/t_ruby/cache.rb', line 763

def to_h
  @timings.map do |name, time|
    {
      name: name,
      total_time: time,
      call_count: @call_counts[name],
      avg_time: time / @call_counts[name]
    }
  end
end