in reply to Re: performance of perl vs java
in thread performance of perl vs java

But this will find 3,000,000 over six times in a second:

use strict; use warnings; use feature 'say'; use Benchmark qw/timethis/; use Inline 'C'; my $search_to = 3000000; timethis -10, \&eratos_inline_c; # Thin wrapper to bind input params for the benchmark. sub eratos_inline_c { return @{inline_c_pa_eratos_primes( $search_to )}; } __DATA__ __C__ /* Find all primes up to 'search_to' using the Sieve of Eratosthenes. +*/ AV * inline_c_pa_eratos_primes ( int search_to ) { AV* av = newAV(); int* primes = 0; int i; Newx( primes, search_to + 1 , int ); if( ! primes ) croak( "Failed to allocate memory.\n" ); for( i = 0; i <= search_to; i++ ) primes[i] = 1; for( i = 2; i * i <= search_to; i++ ) { if( primes[i] ) { int j; for( j = i; j * i <= search_to; j++ ) primes[ i * j ] = 0; } } for( i = 2; i <= search_to; i++ ) { if( primes[i] == 1 ) av_push( av, newSViv( i ) ); } Safefree( primes ); return sv_2mortal( av ); }

Dave

Replies are listed 'Best First'.
Re^3: performance of perl vs java
by repellent (Priest) on Oct 30, 2011 at 19:59 UTC
    Thanks for the Inline C approach. That showcases one of Perl's strengths: to be able to dive down lower-level to C (via XS) and glue it back to Perl-land if we need the extra performance, all with minimal effort.

    I'm curious - how long does my Perl primes(3_000_000) take on your machine?

    Also, what are your machine specs?