Sha256: 6958b104d98c091ea932f1037d968b38c3400c81182b7f533e09e4f751e6caf4

Contents?: true

Size: 1.48 KB

Versions: 37

Compression:

Stored size: 1.48 KB

Contents

require "./lib/contracts"
require "benchmark"
require "rubygems"
require "method_profiler"
require "ruby-prof"

include Contracts

def add opts
  opts[:a] + opts[:b]
end

Contract ({ :a => Num, :b => Num}) => Num
def contracts_add opts
  opts[:a] + opts[:b]
end

def explicit_add opts
  a = opts[:a]
  b = opts[:b]
  fail unless a.is_a?(Numeric)
  fail unless b.is_a?(Numeric)
  c = a + b
  fail unless c.is_a?(Numeric)
  c
end

def benchmark
  Benchmark.bm 30 do |x|
    x.report "testing add" do
      1_000_000.times do |_|
        add(:a => rand(1000), :b => rand(1000))
      end
    end
    x.report "testing contracts add" do
      1_000_000.times do |_|
        contracts_add(:a => rand(1000), :b => rand(1000))
      end
    end
  end
end

def profile
  profilers = []
  profilers << MethodProfiler.observe(Contract)
  profilers << MethodProfiler.observe(Object)
  profilers << MethodProfiler.observe(Contracts::MethodDecorators)
  profilers << MethodProfiler.observe(Contracts::Decorator)
  profilers << MethodProfiler.observe(Contracts::Support)
  profilers << MethodProfiler.observe(UnboundMethod)
  10_000.times do |_|
    contracts_add(:a => rand(1000), :b => rand(1000))
  end
  profilers.each { |p| puts p.report }
end

def ruby_prof
  RubyProf.start
  100_000.times do |_|
    contracts_add(:a => rand(1000), :b => rand(1000))
  end
  result = RubyProf.stop
  printer = RubyProf::FlatPrinter.new(result)
  printer.print(STDOUT)
end

benchmark
profile
ruby_prof if ENV["FULL_BENCH"] # takes some time

Version data entries

37 entries across 28 versions & 7 rubygems

Version Path
contracts-0.17.2 benchmarks/hash.rb
contracts-0.17.1 benchmarks/hash.rb
entitlements-app-1.1.0 lib/contracts-ruby3/benchmarks/hash.rb
entitlements-app-1.1.0 lib/contracts-ruby2/benchmarks/hash.rb
entitlements-app-1.0.0 lib/contracts-ruby2/benchmarks/hash.rb
entitlements-app-1.0.0 lib/contracts-ruby3/benchmarks/hash.rb
entitlements-app-0.3.4 lib/contracts-ruby3/benchmarks/hash.rb
entitlements-app-0.3.4 lib/contracts-ruby2/benchmarks/hash.rb
entitlements-app-0.3.1 lib/contracts-ruby3/benchmarks/hash.rb
entitlements-app-0.3.1 lib/contracts-ruby2/benchmarks/hash.rb
honeybadger-5.4.0 vendor/bundle/ruby/3.2.0/gems/contracts-0.17/benchmarks/hash.rb
honeybadger-5.3.0 vendor/bundle/ruby/3.2.0/gems/contracts-0.17/benchmarks/hash.rb
entitlements-app-0.3.0 lib/contracts-ruby2/benchmarks/hash.rb
entitlements-app-0.3.0 lib/contracts-ruby3/benchmarks/hash.rb
entitlements-0.2.1 lib/contracts-ruby3/benchmarks/hash.rb
entitlements-0.2.1 lib/contracts-ruby2/benchmarks/hash.rb
entitlements-app-0.2.1 lib/contracts-ruby2/benchmarks/hash.rb
entitlements-app-0.2.1 lib/contracts-ruby3/benchmarks/hash.rb
entitlements-0.2.0 lib/contracts-ruby3/benchmarks/hash.rb
entitlements-0.2.0 lib/contracts-ruby2/benchmarks/hash.rb