Beefy Boxes and Bandwidth Generously Provided by pair Networks
No such thing as a small change
 
PerlMonks  

Re^3: Comparing two arrays

by hdb (Monsignor)
on Dec 15, 2013 at 11:54 UTC ( [id://1067225]=note: print w/replies, xml ) Need Help??


in reply to Re^2: Comparing two arrays
in thread Comparing two arrays

You are right. See the following benchmarks:

use strict; use warnings; use Benchmark 'cmpthese'; sub create { map {rand() < $_[1] ? 1 : 0} 1..$_[0] } sub compare1 { # naive my $x = shift; my $n = shift; return map { my $y=$_; scalar grep { $y->[$_] == 1 and $x->[$_] == 1 + } 0..$n-1 } @_; } sub compare2 { # first find 1s in x, then check in ys my $x = shift; my $n = shift; my @nxs = grep { $x->[$_] } 0..$n-1; return map { my $y=$_; scalar grep { $y->[$_] == 1 } @nxs } @_ ; } sub compare3 { # stringify my $x = shift; $x = join '', @$x; return map { my $j = $x & join'',@$_; $j =~ tr/1/1/ } @_; } my $n = 15000; my $p = 0.005; my $ny = 10; my @x = create $n, $p; my @ys = map { [ create $n, $p ] } 1..$ny; my @r1 = compare1 \@x, $n, @ys; my @r2 = compare2 \@x, $n, @ys; my @r3 = compare3 \@x, @ys; print "compare1: @r1\n"; print "compare2: @r2\n"; print "compare3: @r3\n"; cmpthese( -5, { compare1 => sub{ compare1 \@x, $n, @ys }, compare2 => sub{ compare2 \@x, $n, @ys }, compare3 => sub{ compare3 \@x, @ys }, } );
Results:
Rate compare1 compare3 compare2 compare1 48.8/s -- -81% -91% compare3 253/s 420% -- -53% compare2 537/s 1002% 112% --

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1067225]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others lurking in the Monastery: (3)
As of 2024-04-19 20:00 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found