#! /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%.
In reply to Re: Faster way to do this?
by choroba
in thread Faster way to do this?
by Anonymous Monk
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |