From: Peter Vandenabeele Date: 2012-01-23T23:39:25+09:00 Subject: Re: uniq with count; better way? --20cf300fb11b5e8ff404b732fc1b Content-Type: text/plain; charset=UTF-8 On Mon, Jan 23, 2012 at 3:08 PM, Karsten Meier < developer@handylearn-projects.de> wrote: > Ok, I tried some benchmarks. We have now even more variables, as they > also depend on "maxval" from the dataset. > > maxval = 1000 > ar = [].tap{|a| 1_000_000.times {a << rand(maxval)}} > > b.report("Meier:") { > n.times { > hist = Array.new(maxval+1, 0) > ar.each{|x| hist[x] += 1;} > result = Hash.new(0) > 0.upto(maxval){|i| result[i] = hist[i] unless hist[i] == 0} > result > } > } > > > > On my jruby and my windows- mri 1.8.7 my algorithm was fastest for > maxvalue of 10, 100 or 10000, for example: > > SIZE > 1000000 > MAXVAL > 10000 > user system total real > Ralph Shneiver: 0.533000 0.000000 0.533000 ( 0.518000) > Meier: 0.312000 0.000000 0.312000 ( 0.312000) > Keinich #1 0.814000 0.000000 0.814000 ( 0.814000) > > (I have no 1.9.3 yet on my windows PC, so it may be different there) > Interesting. I added your algorithm to the list and tested on ruby 1.9.3 $ ruby -v ruby 1.9.3p0 (2011-10-30 revision 33570) [i686-linux] SIZE 1000000 MAXVAL 1000 user system total real Ralph Shneiver: 0.370000 0.000000 0.370000 ( 0.369229) Sigurd: 0.420000 0.000000 0.420000 ( 0.418634) Meier: 0.270000 0.000000 0.270000 ( 0.274136) Keinich #1 0.320000 0.000000 0.320000 ( 0.320962) Keinich #2 0.380000 0.000000 0.380000 ( 0.372422) Magnus Holm: 0.420000 0.000000 0.420000 ( 0.423316) Abinoam #1: 0.600000 0.000000 0.600000 ( 0.597028) And I also retested in the latest jruby-head (1.7.0.dev) $ ruby -v jruby 1.7.0.dev (ruby-1.8.7-p357) (2012-01-23 f80ab05) (Java HotSpot(TM) Server VM 1.6.0_26) [linux-i386-java] SIZE 1000000 MAXVAL 1000 user system total real Ralph Shneiver: 0.492000 0.000000 0.492000 ( 0.476000) Sigurd: 0.473000 0.000000 0.473000 ( 0.473000) Meier: 0.287000 0.000000 0.287000 ( 0.287000) Keinich #1 0.308000 0.000000 0.308000 ( 0.308000) Keinich #2 7.374000 0.000000 7.374000 ( 7.374000) Magnus Holm: NoMethodError: undefined method `each_with_object' for # __file__ at sb.rb:30 times at org/jruby/RubyFixnum.java:261 ... So, at least for these 2 cased, your algorithm seems somewhat faster. As long as the array is not "sparsely" populated, this approach certainly makes sense. HTH, Peter --20cf300fb11b5e8ff404b732fc1b--