Skip to content

Instantly share code, notes, and snippets.

@vderyagin
Last active December 10, 2015 11:18
Show Gist options
  • Save vderyagin/4426384 to your computer and use it in GitHub Desktop.
Save vderyagin/4426384 to your computer and use it in GitHub Desktop.
Benchmarking of square root getting operations in different Ruby implementations.
require 'benchmark'
=begin
Math.sqrt(x) is consistently slower then x ** 0.5 in all major ruby implementations.
=end
SIZE = 1e6
ary = Array.new(SIZE) { rand(SIZE) }
Benchmark.bm do |x|
x.report("Math.sqrt:") { ary.map { |item| Math.sqrt(item) } }
x.report("** 0.5: ") { ary.map { |item| item ** 0.5} }
end
=begin
Results:
ruby 1.8.7 (2012-10-12 patchlevel 371) [x86_64-linux]
user system total real
Math.sqrt: 0.500000 0.020000 0.520000 ( 0.546235)
** 0.5: 0.340000 0.020000 0.360000 ( 0.379318)
ruby 1.9.3p362 (2012-12-25 revision 38607) [x86_64-linux]
user system total real
Math.sqrt: 0.860000 0.020000 0.880000 ( 0.925877)
** 0.5: 0.280000 0.010000 0.290000 ( 0.377911)
ruby 2.0.0dev (2012-12-21 trunk 38523) [x86_64-linux]
user system total real
Math.sqrt: 0.480000 0.000000 0.480000 ( 0.513030)
** 0.5: 0.230000 0.000000 0.230000 ( 0.243301)
jruby 1.7.1 (1.9.3p327) 2012-12-03 30a153b on Java HotSpot(TM) 64-Bit Server VM 1.7.0_10-b18 [linux-amd64]
user system total real
Math.sqrt: 1.350000 0.030000 1.380000 ( 1.472000)
** 0.5: 0.210000 0.010000 0.220000 ( 0.225000)
rubinius 2.0.0rc1 (1.8.7 a06055d7 2012-11-02 JI) [x86_64-unknown-linux-gnu]
user system total real
Math.sqrt: 1.564762 0.022997 1.587759 ( 1.996607)
** 0.5: 0.718890 0.005999 0.724889 ( 0.810936)
=end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment