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