Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: Challenge: CPU-optimized byte-wise or-equals (for a meter of beer)

by ikegami (Patriarch)
on Sep 12, 2007 at 14:13 UTC ( [id://638561]=note: print w/replies, xml ) Need Help??


in reply to Challenge: CPU-optimized byte-wise or-equals (for a meter of beer)

Bit ops?

sub using_str_bit_ops_and_s { my ($s1, $s2) = @_; (my $mask = $s1) =~ s/[^\x00]/\xFF/g; return ($s1 & $mask) | ($s2 & ~$mask); }

tr should be faster.

sub using_str_bit_ops_and_tr { my ($s1, $s2) = @_; (my $mask = $s1) =~ tr/\x00/\xFF/c; return ($s1 & $mask) | ($s2 & ~$mask); }

Benchmarks:

Rate split1 substr1 bit_ops map_split split1 1.25/s -- -95% -100% -100% substr1 25.5/s 1939% -- -96% -99% bit_ops 642/s 51313% 2421% -- -71% map_split 2230/s 178496% 8657% 247% --

Corion's solution humbles my ass-kicking solution! I wonder if a higher density of zeros would boost my rating?

Update: Added tr variant.
Update: Added Benchmarks.

Replies are listed 'Best First'.
Re^2: Challenge: CPU-optimized byte-wise or-equals (for a meter of beer)
by bart (Canon) on Sep 12, 2007 at 16:17 UTC
    Bit ops?
    sub using_str_bit_ops_and_s { my ($s1, $s2) = @_; (my $mask = $s1) =~ tr/\x00/\xFF/c; return ($s1 & $mask) | ($s2 & ~$mask); }
    I was thinking in the same direction, except I'd use xor. After all, ((A xor B ) and 0) xor B is B, and ((A xor B) and true) xor B is A, for any value of A and B.

    So:

    sub using_str_bit_xor { my ($s1, $s2) = @_; (my $mask = $s1) =~ tr/\x00/\xFF/c; return (($s1 ^ $s2) & $mask ) ^ $s2; }

    Benchmarks: (and yes I did use 64k byte strings):

    my $x = pack 'C*', map int rand(256), 1 .. 64*1024; my $y = pack 'C*', map int rand(256), 1 .. 64*1024; using_str_bit_ops_and_s($x, $y) eq using_str_bit_xor($x, $y) or die "Results are different??"; use Benchmark 'cmpthese'; cmpthese -3, { using_str_bit_ops_and_s => sub{ my $r = using_str_bit_ops_and_s($x, +$y) }, using_str_bit_xor=> sub{ my $r = using_str_bit_xor($x, $y) }, };
    Result:
    Rate using_str_bit_ops_and_s using_str_ +bit_xor using_str_bit_ops_and_s 686/s -- + -16% using_str_bit_xor 821/s 20% + --
    The speed gain is humble, but real.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others about the Monastery: (2)
As of 2024-04-24 23:26 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found