Skip to content

Instantly share code, notes, and snippets.

@timuruski
Last active August 29, 2015 13:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timuruski/9120387 to your computer and use it in GitHub Desktop.
Save timuruski/9120387 to your computer and use it in GitHub Desktop.
Benchmarking sort strategies in Ruby.
require 'benchmark'
a = Array.new(10_000) { rand }
Benchmark.bm(20) do |bench|
bench.report('sort <=>') { 10.times { a.sort { |x,y| y <=> x } } }
bench.report('sort.reverse') { 10.times { a.sort.reverse } }
bench.report('sort_by.reverse') { 10.times { a.sort_by(&:to_f).reverse } }
end
# user system total real
# sort <=> 0.130000 0.000000 0.130000 ( 0.131826)
# sort.reverse 0.070000 0.000000 0.070000 ( 0.066339)
# sort_by.reverse 0.070000 0.000000 0.070000 ( 0.070748)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment