Skip to content

Instantly share code, notes, and snippets.

@BrianMehrman
Last active September 15, 2016 21:04
Show Gist options
  • Save BrianMehrman/6e0adb23d1db5fa0013813a4592d7c66 to your computer and use it in GitHub Desktop.
Save BrianMehrman/6e0adb23d1db5fa0013813a4592d7c66 to your computer and use it in GitHub Desktop.
require 'benchmark/ips'
module ExtraMath
def self.build_math(attr_name)
attr_name = attr_name.to_s
class_eval %Q{
def #{attr_name}(x)
x + x
end
}
end
build_math(:do_mathes)
define_method "do_maths" do |x|
x + x
end
def do_math(x)
x + x
end
end
class TestMath
include ExtraMath
end
t = TestMath.new
Benchmark.ips do |x|
# Configure the number of seconds used during
# the warmup phase (default 2) and calculation phase (default 5)
x.config(:time => 5, :warmup => 2)
# These parameters can also be configured this way
x.time = 5
x.warmup = 2
x.report("normal maths") do
t.do_math(2)
end
x.report("define_method maths") do
t.do_maths(2)
end
x.report("class_eval maths") do
t.do_mathes(2)
end
x.compare!
end
@BrianMehrman
Copy link
Author

This gist is here to test the performance of define_method vs class_eval at runtime. You will need to have Benchmark-IPS installed to run this gist.

@BrianMehrman
Copy link
Author

Warming up --------------------------------------
        normal maths   217.946k i/100ms
 define_method maths   200.375k i/100ms
    class_eval maths   234.464k i/100ms
Calculating -------------------------------------
        normal maths      7.040M (± 7.8%) i/s -     35.089M in   5.016121s
 define_method maths      5.294M (±11.1%) i/s -     26.049M in   5.011117s
    class_eval maths      7.051M (± 7.7%) i/s -     35.170M in   5.019806s

Comparison:
    class_eval maths:  7051160.4 i/s
        normal maths:  7040465.6 i/s - same-ish: difference falls within error
 define_method maths:  5294350.6 i/s - 1.33x  slower

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment