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.

5 Comments

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.

use Benchmark ":hireswallclock";

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:

my $tree_expected = 'some fancy stuff';
my $tree_got;

my $time_spent = timeit( 
sub { $tree_got = $p->parse($input) } );

is $tree_got, $tree_expected, "parsed in $time_spent seconds"

Thanks for the hint.

About Ovid

user-pic Freelance Perl/Testing/Agile consultant and trainer. See http://www.allaroundtheworld.fr/ for our services. If you have a problem with Perl, we will solve it for you. And don't forget to buy my book! http://www.amazon.com/Beginning-Perl-Curtis-Poe/dp/1118013840/