Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # coding: utf-8
- require 'active_support/core_ext/string/conversions.rb'
- require 'benchmark/ips'
- data = ([
- '11/15/2015',
- '11/29/2015',
- '11/11/2015',
- '11/5/2015',
- '11/18/2015',
- '11/1/2015',
- '11/11/2015',
- '11/30/2015',
- '11/6/2015',
- '11/4/2015'
- ] * 1000).shuffle
- def naive_sort(ary)
- ary.sort { |a, b| Time.strptime(b, '%m/%d/%Y') <=> Time.strptime(a, '%m/%d/%Y') }
- end
- def sort_by(ary)
- ary.sort_by { |x| Time.strptime(x, '%m/%d/%Y') }.reverse
- end
- Benchmark.ips do |x|
- x.report('sort by') { sort_by(data) }
- x.report('naive') { naive_sort(data) }
- x.compare!
- end
- __END__
- % ruby benchmarks.rb
- Warming up --------------------------------------
- sort by 1.000 i/100ms
- naive 1.000 i/100ms
- Calculating -------------------------------------
- sort by 9.721 (± 0.0%) i/s - 49.000 in 5.045643s
- naive 2.228 (± 0.0%) i/s - 12.000 in 5.390025s
- Comparison:
- sort by: 9.7 i/s
- naive: 2.2 i/s - 4.36x slower
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement