Beefy Boxes and Bandwidth Generously Provided by pair Networks
laziness, impatience, and hubris
 
PerlMonks  

Re^3: Request to correct the perl code for getting substrings

by oldtomas (Novice)
on Apr 20, 2012 at 06:57 UTC ( #966107=note: print w/replies, xml ) Need Help??


in reply to Re^2: Request to correct the perl code for getting substrings
in thread Request to correct the perl code for getting substrings

Don't use $&, it will slow down every regular expression in the program
You're quite right, Sir ;-)
#!/usr/bin/perl -w use Benchmark; my $string = "CCATGNNNTAACCNNATGNNTAGCC" x 10000; timethese(10, { 'matchamp' => sub {matchamp($string)}, 'matchpar' => sub {matchpar($string)}, }); sub matchamp { my $string = shift; my $matchlen = 0; while($string =~ /[AG]TG.*?[AG][AG]/g) { $matchlen += length($&); # Actually reference $& to keep Perl from + cheating } return $matchlen; } sub matchpar { my $string = shift; my $matchlen = 0; while ( $string =~ /([AG]TG.*?T[AG][AG])/g ) { $matchlen += length($1); # Reference $1, for fairness } return $matchlen; }
yields:
Benchmark: timing 10 iterations of matchamp, matchpar... matchamp: 24 wallclock secs (23.48 usr + 0.00 sys = 23.48 CPU) @ 0 +.43/s (n=10) matchpar: 26 wallclock secs (25.70 usr + 0.00 sys = 25.70 CPU) @ 0 +.39/s (n=10)

The "$&" leg seems a tad faster, right?

BUT...

removing every trace of matchamp in the above program yields:

Benchmark: timing 10 iterations of matchpar... matchpar: 1 wallclock secs ( 0.54 usr + 0.00 sys = 0.54 CPU) @ 18 +.52/s (n=10)

That's a speedup by a factor ~26. I'm impressed.

Thanks for pointing that out

Log In?
Username:
Password:

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://966107]
help
Chatterbox?
[marto]: Corion Schoenfeld, but my friend has been telling me about this new airport for about 7-8 years now :P
[marto]: I doubt it even exists as a building site :P
[ambrus]: Corion: does building airports "somewhat outside of" a city ever work? cities always grow around the airport quickly, because it's practical to be close to it, and after that, people start to complain that the airplanes land so close to their house and sh
[ambrus]: ould keep down the noise

How do I use this? | Other CB clients
Other Users?
Others rifling through the Monastery: (7)
As of 2017-02-23 12:04 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    Before electricity was invented, what was the Electric Eel called?






    Results (346 votes). Check out past polls.