Sha256: 01edf948088b0d37656dccf22b2de6d15b5d762533cef0289915f6d49eca7513

Contents?: true

Size: 1.46 KB

Versions: 1

Compression:

Stored size: 1.46 KB

Contents

require 'stringio'
require 'benchmark'

# == Overview
#
# The ThreadsafeBenchmark module provides methods for benchmarking Ruby 
# code in a thread-safe manner. Use it as you would the standard Benchmark
# module.

module ThreadsafeBenchmark
  include Benchmark
  
  class Report
    def initialize(width = 0, fmtstr = nil)
      @width, @fmtstr = width, fmtstr
    end

    def item(label = "", *fmt, &blk) # :yield:
      Thread.current["io"] << label.ljust(@width)
      res = Benchmark::measure(&blk)
      Thread.current["io"] << res.format(@fmtstr, *fmt)
      res
    end

    alias :report :item
  end

  def threadsafe_benchmark(caption = "", label_width = nil, fmtstr = nil, *labels)
    Thread.current["io"] = StringIO.new
    label_width ||= 0
    fmtstr ||= Benchmark::FMTSTR
    raise ArgumentError, "no block" unless iterator?
    unless Thread.main["caption"]
      puts caption
      Thread.main["caption"] = true
    end
    results = yield(ThreadsafeBenchmark::Report.new(label_width, fmtstr))
    Array === results and results.grep(Tms).each {|t|
      Thread.current["io"] << (labels.shift || t.label || "").ljust(label_width)
      Thread.current["io"] << t.format(fmtstr)
    }
    puts Thread.current["io"].string
  end
  alias :ts_benchmark :threadsafe_benchmark

  def threadsafe_bm(label_width = 0, *labels, &blk)
    threadsafe_benchmark(" "*label_width + Benchmark::CAPTION, label_width, Benchmark::FMTSTR, *labels, &blk)
  end
  alias :ts_bm :threadsafe_bm
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
threadsafe_benchmark-1.0.0 lib/threadsafe_benchmark.rb