InfiniteSilence has asked for the wisdom of the Perl Monks concerning the following question:

So I'm finally getting into the habit of benchmarking while I'm coding and I run across this article online. I like it but I hate to type the entire function, so I figure I'll read it from a file, like so:
use Benchmark; my $code = ''; print "Enter number of code runs:\n"; my $runs = <STDIN>; chomp ($runs); print "Inline or load up code(1|2)?\n"; my $inline = <STDIN>; chomp($inline); if($inline == 1) { $/ = "#END"; print "Enter code block (end with #END):\n"; $code = <STDIN>; chomp($code); print "\n...Testing...\n"; timethis($runs, $code); } else { my $file; my $func; print "Give me the file name: \n"; $file = <STDIN>; chomp($file); $code = `cat $file`; eval($code); die $@ if $@; if($code=~m/sub\s+(\w+)/) { $func = $1; } no strict 'refs'; print "\n...Testing...\n"; timethis($runs, &$func); }
In case you are interested, here is the dummy function it is trying to run:
sub manic { my $x = 0; for (0..50) { $x++; } print $x; }
When I run this with the code option I get the following:
:)~> perl bmark.pl Enter number of code runs: 2000 Inline or load up code(1|2)? 2 Give me the file name: test.al ...Testing... 51timethis 2000: 0 wallclock secs ( 0.00 usr + 0.00 sys = 0.00 CPU) (warning: too few iterations for a reliable count)
See? It just ran one time. If I manually type in the manic function's code it will run all 2000 times. What gives?

Celebrate Intellectual Diversity

Replies are listed 'Best First'.
Re: Benchmark Runs Only Once
by Corion (Patriarch) on Sep 30, 2010 at 16:44 UTC

    &$func does not give you a reference to the function, it calls the function:

    > perl -wle "sub foo { print 'In foo' }; my $func='foo'; &$func" In foo

    Had you used strict, Perl would have prevented you from making this error.

    > perl -Mstrict -wle "sub foo { print 'In foo' }; my $func='foo'; &$fu +nc" Can't use string ("foo") as a subroutine ref while "strict refs" in us +e at -e line 1.
      Using strict wouldn't have helped since he wants to get a reference to a symbol named in a variable. He should still use it, though, and just disable it where he needs it disable.
      timethese(..., do { no strict 'refs'; \&$func });

      An alternative solution comes from the realisation that timethese can also take a string of Perl code.

      timethese(..., $func.'()');
Re: Benchmark Runs Only Once
by JavaFan (Canon) on Oct 01, 2010 at 13:57 UTC
    I'm finally getting into the habit of benchmarking while I'm coding
    You say this as if you think this is a good thing.