http://www.perlmonks.org?node_id=21721


in reply to RE: RE: sieve of erothenes
in thread sieve of erothenes

Very slick! I've never seen it done like this before. We're not using the same algorithm, but for my own morbid curiosity I benchmarked it against mine and ase's code. I added the 'o' modifier to your regex to speed it up a bit.
#!usr/bin/perl -w use Benchmark; timethese(100,{ Maverick => sub { for (1..1000){ push @_,$_; for (@_[1..$#_-1]){ pop @_ && last if !($_[-1]%$_) } } #print join "\t", @_; }, Ase => sub { $v='1' x 1000; for(2..1000){ next if !vec($v,$_-1,8); for($q=$_*2;$q<1001;$q+=$_){ vec($v,$q-1,8)=0 } } #print join "\t",grep {vec($v,$_-1,8)} (1..100 +0); }, Alan => sub { for(1..1000){ push @_,$_ if (1 x $_) !~ /^1?$|^(11+? +)\1+$/o } #print join "\t", @_; } });
and ended up with:
Benchmark: timing 100 iterations of Alan, Ase, Maverick... Alan: 93 wallclock secs (92.95 usr + 0.00 sys = 92.95 CPU) Ase: 1 wallclock secs ( 1.03 usr + 0.00 sys = 1.03 CPU) Maverick: 1 wallclock secs ( 1.65 usr + 0.01 sys = 1.66 CPU)
You have the shortest but ase still has the fastest. :)

This started off being about the seive of "the always mispelled guy", but now I'm curious about other ways of doing this. Perhaps on some rainy afternoon I'll go dig up few more interesting snippets to throw at the monk collective...

/\/\averick