Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

Re: Faster way to do this?

by choroba (Cardinal)
on Nov 12, 2015 at 16:55 UTC ( [id://1147594]=note: print w/replies, xml ) Need Help??


in reply to Faster way to do this?

This seems a bit faster:
#! /usr/bin/perl use warnings; use strict; my $start = tell DATA; sub orig { seek DATA, $start, 0; my $count = 0; while (<DATA>) { while (/(M+)/g) { $count++; } } return $count } sub ch { my $count = 0; seek DATA, $start, 0; while (<DATA>) { tr/M/M/s; # tr/MIO/MIO/s seems a bit slower for longer inp +uts. $count += tr/M//; } return $count } use Test::More; is(ch(), orig(), 'ch4'); done_testing(); use Benchmark qw{ cmpthese }; cmpthese(-3, { orig => \&orig, ch => \&ch, }); __DATA__ IIIIIIIIIIIMMMMMMMMMMMMOOOOOOOOOOOOMMMMMMMMMIIIIIIIIIMM IIIIIIMMMMOOOOOMMMMIIIIIIIIIIIIIMMIIII MIM IMI M

On my machine:

ok 1 - ch4 1..1 Rate orig ch orig 59645/s -- -34% ch 89860/s 51% --

I tested various other approaches ($count += () = /M+/g, split), but your original's speed was always the same or better.

Update: It seems to scale better with longer inputs, for 15K string, it shows 280%.

لսႽ† ᥲᥒ⚪⟊Ⴙᘓᖇ Ꮅᘓᖇ⎱ Ⴙᥲ𝇋ƙᘓᖇ

Log In?
Username:
Password:

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

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

    No recent polls found