Nice! Benchmark of various solutions (I hope I did not spoil it again):
Output on my machine:
1..5
ok 1 - double negation
ok 2 - single - classic
ok 3 - classic - long
ok 4 - classic - translate
ok 5 - classic - str
Rate single translate long classic str
single 0.328/s -- -100% -100% -100% -100%
translate 161/s 48834% -- -26% -39% -59%
long 217/s 66040% 35% -- -18% -45%
classic 263/s 80093% 64% 21% -- -33%
str 394/s 119839% 145% 81% 50% --
| [reply] [d/l] [select] |
C:\test>1046579 -N=2**20
1048576
Rate single long classic str translate
single 1.72/s -- -99% -100% -100% -100%
long 134/s 7707% -- -71% -79% -81%
classic 468/s 27047% 248% -- -26% -33%
str 632/s 36579% 370% 35% -- -9%
translate 695/s 40233% 417% 49% 10% --
C:\test>1046579 -N=2**30
1073741824
(warning: too few iterations for a reliable count)
(warning: too few iterations for a reliable count)
s/iter str translate
str 1.96 -- -21%
translate 1.54 27% --
The modified code: #! perl -slw
use strict;
use Benchmark qw(cmpthese);
sub single {
${ $_[0] } =~ s/(.)/~$1/ges;
}
sub long {
${ $_[0] } =~ s/(.{1,10000})/~$1/ges;
}
sub classic {
${ $_[0] } = ~${ $_[0] };
}
sub str {
my $blocksize = 10000;
my $lb = length ${ $_[0] };
my $offset = 0;
while( $offset < $lb ) {
substr ${ $_[0] }, $offset, $blocksize,
~substr( ${ $_[0] }, $offset, $blocksize );
$offset += $blocksize;
}
}
BEGIN {
my $rev = join '', map sprintf( "\\x%02x", $_ ), reverse 0 .. 25
+5;
eval "sub translate { \${ \$_[0] } =~ tr[\\x00-\\xff][$rev] } ; 1
+" or die $@;
}
our $N //= 256; $N = eval "0+$N"; #print $N;
our $bits = pack 'C*', 0 .. 255;
$bits x= ( $N / 256 );
cmpthese -3, {
# classic => q[ classic( \$bits) ],
# single => q[ single( \$bits ) ],
# long => q[ long( \$bits ) ],
translate => q[ translate( \$bits ) ],
str => q[ str( \$bits ) ],
};
With the rise and rise of 'Social' network sites: 'Computers are making people easier to use everyday'
Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.
| [reply] [d/l] [select] |
I am confused. Is not $_[0] aliased to the function argument? Why using all those references and dereferences? Moreover, running your code with N=2**29, I am still getting
single 6.13e-03/s -- -100% -100% -100% -100%
long 2.97/s 48381% -- -1% -35% -58%
translate 3.01/s 48989% 1% -- -35% -58%
classic 4.60/s 74981% 55% 53% -- -36%
str 7.14/s 116486% 140% 137% 55% --
With 2**30, it dies with Substitution loop at ./7.pl line 10.
Update: This is perl 5, version 16, subversion 0 (v5.16.0) built for x86_64-linux-thread-multi
| [reply] [d/l] [select] |