Advertisement
Guest User

Untitled

a guest
Oct 26th, 2016
61
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.02 KB | None | 0 0
  1. # coding: utf-8
  2. require 'active_support/core_ext/string/conversions.rb'
  3. require 'benchmark/ips'
  4.  
  5. data = ([
  6. '11/15/2015',
  7. '11/29/2015',
  8. '11/11/2015',
  9. '11/5/2015',
  10. '11/18/2015',
  11. '11/1/2015',
  12. '11/11/2015',
  13. '11/30/2015',
  14. '11/6/2015',
  15. '11/4/2015'
  16. ] * 1000).shuffle
  17.  
  18. def naive_sort(ary)
  19. ary.sort { |a, b| Time.strptime(b, '%m/%d/%Y') <=> Time.strptime(a, '%m/%d/%Y') }
  20. end
  21.  
  22. def sort_by(ary)
  23. ary.sort_by { |x| Time.strptime(x, '%m/%d/%Y') }.reverse
  24. end
  25.  
  26. Benchmark.ips do |x|
  27. x.report('sort by') { sort_by(data) }
  28. x.report('naive') { naive_sort(data) }
  29.  
  30. x.compare!
  31. end
  32.  
  33. __END__
  34. % ruby benchmarks.rb
  35.  
  36. Warming up --------------------------------------
  37. sort by 1.000 i/100ms
  38. naive 1.000 i/100ms
  39. Calculating -------------------------------------
  40. sort by 9.721 (± 0.0%) i/s - 49.000 in 5.045643s
  41. naive 2.228 (± 0.0%) i/s - 12.000 in 5.390025s
  42.  
  43. Comparison:
  44. sort by: 9.7 i/s
  45. naive: 2.2 i/s - 4.36x slower
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement