Skip to content

Instantly share code, notes, and snippets.

@hrp
Created November 28, 2016 23:54
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 hrp/a795f6db1d32083064571910ce702ee7 to your computer and use it in GitHub Desktop.
Save hrp/a795f6db1d32083064571910ce702ee7 to your computer and use it in GitHub Desktop.
#!/usr/bin/ruby
require 'benchmark'
puts "Running Ruby #{RUBY_VERSION}"
ary = []
200.times {
ary << {:bar => Time.at(rand * Time.now.to_i)}
}
n = 1000
puts "n=#{n}"
Benchmark.bm(20) do |x|
x.report("sort") { n.times { ary.dup.sort{ |a,b| b[:bar] <=> a[:bar] } } }
x.report("sort reverse") { n.times { ary.dup.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
x.report("sort_by Time-a[:bar]") { n.times { ary.dup.sort_by{ |a| Time.now - a[:bar] } } }
x.report("sort_by Time-a[:bar]") { n.times { ary.dup.sort_by{ |a| Time.now - a[:bar].to_i } } }
x.report("sort_by 0-a[:bar]") { n.times { ary.dup.sort_by{ |a| -a[:bar].to_i } } }
x.report("sort_by a[:bar]*-1") { n.times { ary.dup.sort_by{ |a| a[:bar].to_i*-1 } } }
x.report("sort_by.reverse") { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse } }
x.report("sort_by.reverse!") { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse! } }
end
@hrp
Copy link
Author

hrp commented Nov 28, 2016

Running Ruby 2.3.1
n=1000
                           user     system      total        real
sort                   0.790000   0.000000   0.790000 (  0.796230)
sort reverse           0.800000   0.010000   0.810000 (  0.816075)
sort_by Time-a[:bar]   0.630000   0.000000   0.630000 (  0.639630)
sort_by Time-a[:bar]   0.850000   0.010000   0.860000 (  0.865950)
sort_by 0-a[:bar]      0.650000   0.010000   0.660000 (  0.660505)
sort_by a[:bar]*-1     0.640000   0.000000   0.640000 (  0.647548)
sort_by.reverse        0.690000   0.000000   0.690000 (  0.702201)
sort_by.reverse!       0.720000   0.010000   0.730000 (  0.743032)

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