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

Monks

In my current program I wish the user to be given feedback as to the execution time of various sections of the program. As such I have broken the program into a series of logical operations, each contained within a subroutine. I am using the Benchmark module included with perl to measure execution time. Some of the subroutines do not require parameters and thus the following is fine:

use strict; use warnings; use Benchmark; sub stuff() { my $x = 1000000; foreach my $i (1..$x) { print "." } print "\n"; } my $t; $t = timeit(1, \&stuff); print "Timings: ", timestr($t), "\n";

However, some of the stages that I wish to time take parameters that are passed from the command line. the following code demonstrates the problem.

use strict; use warnings; use Benchmark; sub stuff($) { my $x = shift; foreach my $i (1..$x) { print "." } print "\n"; } my $t; $t = timeit(1, \&stuff(1000000)); print "Timings: ", timestr($t), "\n";

The code has no syntax errors and the subroutine runs. However, instead of outputting timings, once the sub has executed the following error is output:

Undefined subroutine &main::SCALAR called at (eval 2) line 1.

Is it possible for me to time code like this... or must I use a different approach. I could use the time function and just find the difference for each subroutine before and after, but this in inflexible and I would rather do it properly.

Thanks in advance,

____________
Arun

Replies are listed 'Best First'.
Re: Timing a Subroutine with Parameters
by broquaint (Abbot) on Jul 21, 2002 at 18:49 UTC
    I think you'll find the error right about here ...
    $t = timeit(1, \&stuff(1000000)); ^
    You're trying to execute a reference that points to the return of the stuff sub. Instead you probably want something like this
    $t = timeit(1, sub { stuff(1000000) });
    If you want to time functions within programs you may also want to check out the Devel::DProf module.
    HTH

    _________
    broquaint