Skip to content

Instantly share code, notes, and snippets.

@romuald
Created October 16, 2012 08:54
Show Gist options
  • Save romuald/3898140 to your computer and use it in GitHub Desktop.
Save romuald/3898140 to your computer and use it in GitHub Desktop.
Perl timing method
=head2 timeit
Measure a block's execution time.
Example usage:
sub do_stuff() {
timeit {
some_method();
# and other stuff probably
};
# ...
timeit {
# another block
};
}
Will output (on STDERR) something like:
Your::Module:14 elapsed in 0.00233s
Your::Module:19 elapsed in 0.01028s
=cut
sub timeit(&@) {
my $coderef = shift;
use Time::HiRes qw//;
my @caller = caller;
my $head = "$caller[0]:$caller[2]";
my ($ret, @ret);
my $start = Time::HiRes::time();
if ( wantarray ) {
@ret = &$coderef(@_);
} else {
$ret = &$coderef(@_);
}
printf STDERR "$head elapsed in %.5fs\n", (Time::HiRes::time() - $start);
if ( wantarray ) {
return @ret;
} else {
return $ret;
}
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment