I found some puzzling instabilities while benchmarking a couple of alternatives that came up in a recent thread.

First the code (the only difference between before.pl and after.pl is that the definitions of $X and $Y are reversed from one to the other):

# before.pl use strict; use warnings; use Benchmark 'cmpthese'; my $sz = ( shift || 10 ) - 4; my $X = 'N' . 'x' x $sz . '000'; my $Y = 'N' . 'x' x $sz . '001'; print '# input length: ', length( $X ), $/; cmpthese( -1, { '?!X' => '$X =~ /^N(?!.*00$).*$/', '?!Y' => '$Y =~ /^N(?!.*00$).*$/', '?<!X' => '$X =~ /^N.*(?<!00$)$/', '?<!Y' => '$Y =~ /^N.*(?<!00$)$/', } ); __END__ # after.pl use strict; use warnings; use Benchmark 'cmpthese'; my $sz = ( shift || 10 ) - 4; my $X = 'N' . 'x' x $sz . '001'; my $Y = 'N' . 'x' x $sz . '000'; print '# input length: ', length( $X ), $/; cmpthese( -1, { '?!X' => '$X =~ /^N(?!.*00$).*$/', '?!Y' => '$Y =~ /^N(?!.*00$).*$/', '?<!X' => '$X =~ /^N.*(?<!00$)$/', '?<!Y' => '$Y =~ /^N.*(?<!00$)$/', } ); __END__

And here's some sample output (I have seen many variations; this example only illustrates the general instability):

% perl before.pl 7 # input length: 7 Rate ?<!Y ?!Y ?<!X ?!X ?<!Y 1553555/s -- -70% -75% -77% ?!Y 5222982/s 236% -- -17% -22% ?<!X 6285324/s 305% 20% -- -6% ?!X 6718816/s 332% 29% 7% -- % perl after.pl # input length: 7 Rate ?<!X ?!Y ?<!Y ?!X ?<!X 2414483/s -- -1% -4% -19% ?!Y 2434774/s 1% -- -3% -18% ?<!Y 2506841/s 4% 3% -- -16% ?!X 2970871/s 23% 22% 19% --
Note that the fastest alternative in before.pl is more than twice as fast as the fastest one in after.pl. Likewise the ratio between the fastest and the slowest in before.pl is much greater than the same ratio in after.pl.

What's going on?

the lowliest monk


In reply to Benchmarking instability by tlm

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.