From: Martin Jansson Date: 2005-09-11T16:41:32+09:00 Subject: Re: Better Random benchmark - need help with profiling On Sat, 10 Sep 2005 21:34:44 +0200, Brian Schr�der wrote: > class RandomNumberGenerator > def initialize(seed = 42) > @seed = seed > end > def random(max) > (max * (@seed = (@seed * 3877 + 29573) % 139968)).quo(139968) > end > end > rng = RandomNumberGenerator.new > (ARGV[0].to_i-1).times do > rng.random(100) > end > puts "%.9f" % rng.random(100) > bschroed@black:~/svn/projekte/random$ ruby benchmark-random.rb user system total real > Original 0.020000 0.050000 9.620000 ( > 9.583356) > Rubiesque 0.010000 0.060000 9.820000 ( > 9.792614) >As you see, it is quite cheap to write prettier code. And the modified > version even keeps the state in a class-variable, so you can have > multiple rng's with differen states around. Shroeder! What version of Ruby do you use? I did something similar in one of my many versions. And it is the oo thing to do. (I haven't actually benchmarked puts vs printf, I will do that ;) It's not faster on my system. That may be proof that profiling is a bad thing and that we all should prove our code mathematically (shudder). martinjansson$ time ruby "random_shroeder.rb" 900000 75.544410151 real 0m10.296s user 0m9.760s sys 0m0.060s martinjansson$ time ruby "random.rb" 900000 75.544410151 real 0m9.984s user 0m9.230s sys 0m0.020s martinjansson$ ruby "random_benchmark.rb" 200 5000 user system total real Ugly 0.100000 0.380000 24.770000 ( 26.368260) Rubiesque 0.130000 0.370000 25.580000 ( 27.071112) martinjansson$ ruby "random_benchmark.rb" 10 900000 user system total real Ugly 0.000000 0.010000 85.770000 ( 98.821162) Rubiesque 0.000000 0.020000 99.810000 (105.068127) Here is the benchmark code: #random_benchmark.rb require 'benchmark' i = ARGV[0].to_i j = ARGV[1].to_i Benchmark.bm(30) do | b | [["random.rb", "Ugly"], ["random_shroeder.rb", "Rubiesque"]].each do | file, title | b.report(title) do i.times do system "ruby #{file} #{j} > /dev/null" end end end end I have a lot of white noise on my system, so I haven't used Rubys benchmark thingie much. It would be more useful to me if it could do matched pair sampling (is that the correct English term?) and/or throw away extreme values.