in reply to performance of perl vs java

If one writes java code in Perl one should not be surprised of the bad performance.

The following is a more perlish version:

use Modern::Perl; use Time::HiRes qw/time/; my $start = time; my $top = 550; my $max = 100; my @primes; my $prime; for ( 2 .. $top ) { $prime = $_; next if $primes[$_]; last unless --$max; { local $_; $primes[ $_ * $prime ] = 1 for 2 .. $top / $prime; } } my $found = time; say $_ for ( grep { !$primes[$_] } 2 .. $prime ); my $end = time; say sprintf "Found all: %.6f seconds", ( $found - $start ); say sprintf "Printing all: %.6f seconds", ( $end - $found ); say sprintf "Running time: %.6f seconds", ( $end - $start );
Output:
2 3 5 7 11 13 17 19 23 29 31 ... 491 499 503 509 521 523 541 Found all: 0.000692 seconds Printing all: 0.000879 seconds Running time: 0.001571 seconds
This application of the Sieve of Erasthotenes finds 100_000 primes in 3 seconds (and then takes 6 seconds to print them on the screen), so it is pretty fast.

CountZero

A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James

Replies are listed 'Best First'.
Re^2: performance of perl vs java
by hbm (Hermit) on Oct 27, 2011 at 23:27 UTC

    Very nice!

    But say sprintf"...", and not printf"...\n"? Just curious.

      I like say, no other reason.

      CountZero

      A program should be light and agile, its subroutines connected like a string of pearls. The spirit and intent of the program should be retained throughout. There should be neither too little or too much, neither needless loops nor useless variables, neither lack of structure nor overwhelming rigidity." - The Tao of Programming, 4.1 - Geoffrey James