Skip to content

Instantly share code, notes, and snippets.

@jgaskins
Created May 18, 2015 17:56
Show Gist options
  • Save jgaskins/2b680390cff632ad7b0c to your computer and use it in GitHub Desktop.
Save jgaskins/2b680390cff632ad7b0c to your computer and use it in GitHub Desktop.
Benchmarking Ruby's Math.sqrt vs raising to the power of 1/2
Calculating -------------------------------------
sqrt 103.322k i/100ms
x ** 0.5 125.661k i/100ms
-------------------------------------------------
sqrt 2.277M (± 6.1%) i/s - 11.365M
x ** 0.5 3.717M (± 5.7%) i/s - 18.598M
Comparison:
x ** 0.5: 3717095.3 i/s
sqrt: 2277003.6 i/s - 1.63x slower
require 'benchmark/ips'
Benchmark.ips do |x|
x.report('sqrt') { Math.sqrt(rand(1024)) }
x.report('x ** 0.5') { rand(1024) ** 0.5 }
x.compare!
end
@chastell
Copy link

Ran these on an i7-3517U CPU @ 1.90GHz.

Ruby 2.2:

ruby 2.2.4p230 (2015-12-16 revision 53155) [x86_64-linux]
Calculating -------------------------------------
                sqrt    75.539k i/100ms
            x ** 0.5   100.807k i/100ms
-------------------------------------------------
                sqrt      2.190M (± 1.4%) i/s -     10.953M
            x ** 0.5      2.947M (± 1.7%) i/s -     14.819M

Comparison:
            x ** 0.5:  2947202.1 i/s
                sqrt:  2190461.8 i/s - 1.35x slower

Ruby 2.3:

ruby 2.3.0preview2 (2015-12-11 trunk 53028) [x86_64-linux]
Calculating -------------------------------------
                sqrt   134.082k i/100ms
            x ** 0.5   110.204k i/100ms
-------------------------------------------------
                sqrt      4.507M (± 1.5%) i/s -     22.660M
            x ** 0.5      3.340M (± 0.6%) i/s -     16.751M

Comparison:
                sqrt:  4507252.8 i/s
            x ** 0.5:  3340189.4 i/s - 1.35x slower

Meanwhile Crystal 0.9.1:

    sqrt 125.28M (± 2.15%)       fastest
x ** 0.5 125.21M (± 2.29%)  1.00× slower

;)

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