Last active
January 7, 2021 02:30
-
-
Save mohawk2/1d44184bb0b5221aba7d0bbdb3926540 to your computer and use it in GitHub Desktop.
Performance comparison looking up indices of set bits in Perl bit-vectors using vec() versus unpack "b*" and regex
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
use strict; | |
use warnings; | |
use Time::HiRes qw(time); | |
my ($SPARSEX, $SPARSEY) = (1100, 1); | |
my $DIMS = 50000; | |
sub set2 { | |
my ($m) = @_; | |
for my $y (0..int($DIMS / $SPARSEY)) { | |
vec($m->[$y * $SPARSEY], $_ * $SPARSEX, 1) = 1 for 0..$DIMS / $SPARSEX; | |
} | |
} | |
sub indget { | |
my ($m, $y, $use_vec) = @_; | |
my $row = $m->[$y]; | |
return [ grep vec($row, $_, 1), 0..$#$m ] | |
if $use_vec; | |
my $s = unpack("b*", $row); | |
my @v; | |
push @v, pos($s) - 1 while $s =~ /1/g; | |
\@v; | |
} | |
$| = 1; | |
my $m = []; | |
my $t = time(); | |
set2($m); | |
printf "set in %0.6f\n", time() - $t; | |
$t = time(); | |
#use Data::Dumper; print Dumper | |
indget($m, 0, 1); | |
printf "with vec done in %0.6f\n", time() - $t; | |
$t = time(); | |
#use Data::Dumper; print Dumper | |
indget($m, 0, 0); | |
printf "with m//g done in %0.6f\n", time() - $t; | |
__END__ | |
set in 1.004957 | |
with vec done in 0.005272 | |
with m//g done in 0.000131 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment