Test::Most and timeit()
I've been doing so much work with algorithm efficiency that you've probably noticed me writing this at the top of a lot of my sample code:
use Time::HiRes qw(gettimeofday tv_interval);
sub timefor(&$) {
my $start = [gettimeofday];
$_[0]->();
say sprintf "$_[1]: took %s time" => tv_interval($start);
}
I'm tired of writing this all the time, so I've added it to Test::Most 0.25 (heading to cpan and already on github). I renamed it timeit and the message is optional. Further, the function is only exported if you request it.
use Test::Most 'timeit';
ok 1;
timeit { ok 1 };
timeit { ok 1 } 'message';
done_testing();
For the example above (taken from my tests), it's silly to time the ok() function, but you may find it useful for quick 'n dirty timings. Plus, you can use it for any code, not just tests. The above prints out something like this:
t/timex.t ..
ok 1
ok 2
# t/timex.t line 7: took 0.000124 seconds
ok 3
# message: took 0.000115 seconds
1..3
ok
It will warn if Time::HiRes is not installed.
Update: Fail! The blog title was wrong, so the URL will look strange. Oops.
FWIW, Benchmark also has timeit(). But perhaps Benchmark should be updated use Time::HiRes, since the later has also been a core module since pre-5.8.
But it probably ought to be the default, rather than hidden behind an obscure option. (Not to mention the implementation, which is… interesting.)
Thanks a lot for this small but beautiful enhancement!
Is it possible to make timeit return the time spent to be used as part of the explanation of a test later, like this:
@rns: yes, I could probably do that, but as a temporary measure you could rewrite your code like this:
I'll try to remember to make that change, though.
Thanks for the hint.