class Object

Public Instance Methods

measure(options={}) { || ... } click to toggle source

inspired by Ruby Performance Optimization: Alexander Dymo

# File lib/but/dev_wrapper.rb, line 7
def measure(options={}, &block)
  gc = options[:gc]
  if gc
    GC.start
  else
    GC.disable
  end

  memory_before = `ps -o rss= -p #{Process.pid}`.to_i/1024
  gc_stat_before = GC.stat
  time = Benchmark.realtime do
    yield
  end
  #puts ObjectSpace.count_objects
  if gc
    GC.start(full_mark: true, immediate_sweep: true, immediate_mark: false)
  end
  #puts ObjectSpace.count_objects
  gc_stat_after = GC.stat
  memory_after = `ps -o rss= -p #{Process.pid}`.to_i/1024
  puts({
    RUBY_VERSION => {
      gc: gc ? 'enabled' : 'disabled',
      time: time.round(3),
      gc_count: gc_stat_after[:count] - gc_stat_before[:count],
      memory: "%d MB" % (memory_after - memory_before)
    }
  }.to_json)
end
profile(options={}) { || ... } click to toggle source
# File lib/but/dev_wrapper.rb, line 38
def profile(options={}, &block)
  measure_mode = options[:profile].upcase
  RubyProf.measure_mode = RubyProf.const_get(measure_mode)

  case measure_mode
  when "WALL_TIME" 
    GC.disable
  when "PROCESS_TIME" 
    GC.disable
  when "ALLOCATIONS" 
    #GC.enable_stats
  when "MEMORY" 
    #GC.enable_stats
  else
  end

  result = RubyProf.profile do
    yield
  end

  printer_g = RubyProf::GraphHtmlPrinter.new(result)
  printer_f = RubyProf::FlatPrinter.new(result)
  printer_c = RubyProf::CallTreePrinter.new(result)
  unless measure_mode == "MEMORY"
    printer_g.print(File.open(measure_mode + "_graph.html","w"))
    printer_f.print(File.open(measure_mode + "_flat.txt","w"))
  end
  printer_c.print(options)

  puts "Profiles written for #{measure_mode}"
end