in reply to The sum of absolute differences in the counts of chars in two strings.
I don't suppose there's anything particularly creative about my attempts, and I'm sure they won't compare to the speed of C. But I've been looking for a reason to learn to use Benchmark, so I thought I'd give this a try.
I tried three methods: counting the characters with tr inside an eval, counting with s///g, and splitting the strings into arrays and using grep. Somewhat surprisingly (to me, anyway, as someone who very rarely uses eval), the eval/tr method was by far the slowest. I assume that's from the overhead of eval, but as far as I know, that's necessary, since the variable has to be interpolated. Perhaps it would be faster, as someone upthread suggested, to put the whole thing into a single eval, rather than 52 separate eval calls, but I'm too attached to keeping eval usage as minimal as possible to feel good about that. The grep method was better, but not great, even though I split the strings outside the test. The easy winner was using an s///g regex to count the replacements like tr, but without the need for eval.
abaugher@bannor:~/work/perl/monks$ cat 938978.pl #!/usr/bin/perl use Modern::Perl; use Benchmark qw(:all);; my( $aa, $bb ) = ('',''); $aa .= chr(65 + rand(26)) for (1..50); $bb .= chr(65 + rand(26)) for (1..50); say $aa; say $bb; my @aa = split //, $aa; my @bb = split //, $bb; cmpthese(100000, { 'grep' => \&usinggrep, 'tr' => \&usingtr, 'sg' => \&usingsg, }); sub usinggrep { my $sum = 0; for my $l ('A'..'Z') { my $acount = grep /$l/, @aa; my $bcount = grep /$l/, @bb; $sum += abs($acount-$bcount); } return $sum; } sub usingtr { my $sum = 0; for my $l ('A'..'Z') { my $acount = eval "'$aa' =~ tr[$l][$l]"; my $bcount = eval "'$bb' =~ tr[$l][$l]"; $sum += abs($acount-$bcount); } return $sum; } sub usingsg { my $sum = 0; for my $l ('A'..'Z') { my $acount = $aa =~ s[$l][$l]g || 0; my $bcount = $bb =~ s[$l][$l]g || 0; $sum += abs($acount-$bcount); } return $sum; } abaugher@bannor:~/work/perl/monks$ perl 938978.pl FHORAICOBMUCUMNYLRCUMVAMGXRRCADIZVTZTRENIEOBGNXSQT JIPPTFERERTBOQOPNQSGWDTTOZOTHNXPEKJACSXEQBOAPIMSHI Rate tr grep sg tr 924/s -- -45% -88% grep 1682/s 82% -- -79% sg 7849/s 749% 367% --
Aaron B.
My Woefully Neglected Blog, where I occasionally mention Perl.
|
|---|
| Replies are listed 'Best First'. | |
|---|---|
|
Re^2: The sum of absolute differences in the counts of chars in two strings.
by choroba (Cardinal) on Nov 19, 2011 at 22:08 UTC | |
|
Re^2: The sum of absolute differences in the counts of chars in two strings.
by trizen (Hermit) on Nov 19, 2011 at 21:55 UTC | |
|
Re^2: The sum of absolute differences in the counts of chars in two strings.
by Anonymous Monk on Nov 20, 2011 at 01:03 UTC |