As you can see, the new Rosetta code is 4 times slower, but Eertree is only 2 times slower.Rate rosetta_old rosetta_new eertree rosetta_old 145/s -- -92% -93% rosetta_new 1925/s 1226% -- -13% eertree 2214/s 1424% 15% -- Rate rosetta_old rosetta_new eertree rosetta_old 20.0/s -- -96% -98% rosetta_new 464/s 2218% -- -60% eertree 1166/s 5729% 151% --
Here's the code for those interested:
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; use experimental qw( signatures ); use String::Eertree; sub rosetta_old($str) { my @pal; for my $n (1 .. length $str) { for my $m (1 .. length $str) { my $strrev = ""; my $strpal = substr $str, $n - 1, $m; if ($strpal ne "") { for my $p (reverse 1 .. length $strpal) { $strrev .= substr $strpal, $p - 1, 1; } ($strpal eq $strrev) and push @pal, $strpal; } } } my %seen; return grep ! $seen{$_}++, @pal } sub rosetta($str) { my (@pal, %seen); for my $n (0 .. length($str) - 1) { for my $m (1 .. length $str) { my $strpal = substr $str, $n, $m; push @pal, $strpal if $strpal eq reverse($strpal) && ! $seen{$strpal}++; } } return @pal } my $s = join "", map chr(ord('a') + int rand 26), 1 .. 55 * 2; say $s; my @p1 = 'String::Eertree'->new(string => "$s")->uniq_palindromes; my @p2 = rosetta_old($s); my @p3 = rosetta($s); use Test2::V0 -no_srand => 1; say "Eertree: @p1"; say "Rosetta old: @p2"; say "Rosetta new: @p3"; like \@p2, bag { item $_ for @p1; end() }; like \@p3, bag { item $_ for @p1; end() }; use Benchmark qw{ cmpthese }; cmpthese(-3, { eertree => sub { 'String::Eertree'->new(string => $s)->uniq_palind +romes }, rosetta_old => sub { rosetta_old($s) }, rosetta_new => sub { rosetta($s) }, }); done_testing();
In reply to Re^3: Possessive sub-pattern with non-greedy content + recursion: WHY does this work??
by choroba
in thread Possessive sub-pattern with non-greedy content + recursion: WHY does this work??
by Anonymous Monk
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |