File: bench_count.rb

package info (click to toggle)
ruby-facets 2.9.2-1
  • links: PTS, VCS
  • area: main
  • in suites: wheezy
  • size: 9,824 kB
  • sloc: ruby: 25,483; xml: 90; makefile: 20
file content (58 lines) | stat: -rw-r--r-- 833 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
require 'benchmark'

module Enumerable

  # duplicates

  def duplicates_1
    h1 = {}
    h2 = {}
    each {|i|
      h2[i] = true if h1[i]
      h1[i] = true
    }
    h2.keys
  end

  def duplicates_2
    inject(Hash.new(0)){|h,v| h[v]+=1; h}.reject{|k,v| v==1}.keys
  end

  # uniq_by

  def uniq_by_1 #:yield:
    h = {}; inject([]) {|a,x| h[yield(x)] ||= a << x}
  end

  def uniq_by_2
    inject({}) { |h,x| h[yield(x)] ||= x; h }.values
  end

end

#

Benchmark.bmbm do |x|
  n = 10000
  a = [1,1,2,3,4,4,5,6,7,7]

  # duplicates

  x.report("duplicates_1") do
    n.times { a.duplicates_1 }
  end

  x.report("duplicates_2") do
    n.times { a.duplicates_2 }
  end

  # uniq_by

  x.report("uniq_by_1") do
    n.times { a.uniq_by_1{ |x| x } }
  end

  x.report("uniq_by_2") do
    n.times { a.uniq_by_2{ |x| x } }
  end
end