module MicroBench

Constants

VERSION

Public Class Methods

configure(&block) click to toggle source

Configure MicroBench.

Example usage:

MicroBench.configure do |config|
  config.formatter = proc { |duration| duration.ceil }
end
# File lib/micro_bench.rb, line 11
def configure(&block)
  block.call(configurations)
  nil
end
duration(bench_id = nil) click to toggle source

Give duration of the benchmark

Parameters:

bench_id

Identifier of the benchmark

Returns:

Formatted duration of the given benchmark, or nil if benchmark is unknown.

Example usage:

MicroBench.duration(:my_benchmark)
# File lib/micro_bench.rb, line 67
def duration(bench_id = nil)
  raw = raw_duration(bench_id)
  return nil if raw.nil?
  
  configurations.formatter.call(raw)
end
raw_duration(bench_id = nil) click to toggle source

Give raw duration of the benchmark

Parameters:

bench_id

Identifier of the benchmark

Returns:

Duration of the given benchmark, or nil if benchmark is unknown.

Example usage:

MicroBench.raw_duration(:my_benchmark)
# File lib/micro_bench.rb, line 86
def raw_duration(bench_id = nil)
  benchmarks[benchmark_key(bench_id)]&.duration
end
start(bench_id = nil) click to toggle source

Start a benchmark

Parameters:

bench_id

Identifier of the benchmark

Returns:

A boolean representing success

Example usage:

MicroBench.start(:my_benchmark)

Calling the method multiple times with the same bench_id will restart the benchmark for the given bench_id.

# File lib/micro_bench.rb, line 31
def start(bench_id = nil)
  benchmarks[benchmark_key(bench_id)] = MicroBench::Benchmark.new
  return true
end
stop(bench_id = nil) click to toggle source

Stop a benchmark

Parameters:

bench_id

Identifier of the benchmark

Returns:

A boolean representing success

Example usage:

MicroBench.stop(:my_benchmark)
# File lib/micro_bench.rb, line 48
def stop(bench_id = nil)
  key = benchmark_key(bench_id)
  return false unless benchmarks.key?(key)

  benchmarks[key].stop
end

Private Class Methods

benchmark_key(bench_id = nil) click to toggle source
# File lib/micro_bench.rb, line 100
def benchmark_key(bench_id = nil)
  "#{thread_key}||#{caller_key}||#{bench_id}"
end
benchmarks() click to toggle source
# File lib/micro_bench.rb, line 96
def benchmarks
  @benchmarks ||= {}
end
caller_key() click to toggle source
# File lib/micro_bench.rb, line 108
def caller_key
  caller_location = caller_locations(2..4).detect do |loc|
    !loc.absolute_path.include?(__FILE__)
  end
  "#{caller_location.absolute_path}:#{caller_location.base_label}"
end
configurations() click to toggle source
# File lib/micro_bench.rb, line 92
def configurations
  @configurations ||= Configurations.new
end
thread_key() click to toggle source
# File lib/micro_bench.rb, line 104
def thread_key
  Thread.current.object_id
end