From: "Aleksi Niemelä" Date: 2001-01-23T02:54:53+09:00 Subject: [ruby-talk:9728] Re: Ruby vs. Python and Euphoria: sieve benc hmark > Kenneth Rhodes writes: > > > Hi..... I am a Ruby novice, really just a curious inquirer. I would > > appreciate someone translating the attached python sieve benchmark > > to RUBY, it would really help me get a handle on the way Ruby is > > written. Dave: > I didn't unpack your code, but you'll find python, Ruby, perl, and > other Sieve benchmarks at: > > http://www.bagley.org/~doug/shootout/bench/sieve/ > > Click on the language to see the source. I became curious a little and thought to translate the original source. I wrapped it to a class, but didn't touch the original logic. class Sieve attr_accessor :size, :flags def initialize(size = 500) @size = size end def sieve count = 0 @flags = Array.new(@size + 1, true) for i in 1..@size if @flags[i] prime = 2 * i prime = prime + 1 start = prime + i start.step(@size, prime) do |k| @flags[k] = false end count += 1 end end return count end end def benchmark(sieve, seconds = 15, batch = 50) puts "prime sieve benchmark" cycles = 0 t = Time.now while Time.now < t + seconds batch.times do nprimes = sieve.sieve puts "whoops!" unless nprimes == 167 end cycles += batch end t = Time.now - t puts "#{cycles / t} sieves per second" print "%3d " % 2 1.upto(sieve.size) do |i| print "%3d " % (i*2 + 1) if sieve.flags[i] end puts end benchmark( Sieve.new(size = 500), seconds = 15, batch = 50) The results: sieve.py: 235.178 sieves per second (15.11user) sieve.rb: 225.616033 sieves per second (15.02user) Lefts me wonder why the Ruby test at Dougs site was dramatically faster than Python, but in this version was slightly slower (except that this one used less wall clock time :). I don't have time to investigate though. - Aleksi