Created
October 16, 2012 08:54
-
-
Save romuald/3898140 to your computer and use it in GitHub Desktop.
Perl timing method
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
=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