Skip to content

Commit

Permalink
turned i into a benchmark function
Browse files Browse the repository at this point in the history
  • Loading branch information
kraih committed Aug 10, 2014
1 parent cb8f27d commit 1b90a7a
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 14 deletions.
14 changes: 7 additions & 7 deletions lib/ojo.pm
@@ -1,7 +1,7 @@
package ojo;
use Mojo::Base -strict;

use Benchmark qw(timeit :hireswallclock);
use Benchmark qw(timeit timestr :hireswallclock);
use Mojo::ByteStream 'b';
use Mojo::Collection 'c';
use Mojo::DOM;
Expand Down Expand Up @@ -30,7 +30,7 @@ sub import {
d => sub { _request($ua, 'DELETE', @_) },
g => sub { _request($ua, 'GET', @_) },
h => sub { _request($ua, 'HEAD', @_) },
i => sub (&@) { timeit($_[1] // 1, $_[0])->[0] },
i => sub (&@) { say STDERR timestr timeit($_[1] // 1, $_[0]) },
j => \&j,
o => sub { _request($ua, 'OPTIONS', @_) },
p => sub { _request($ua, 'POST', @_) },
Expand Down Expand Up @@ -138,13 +138,13 @@ L<Mojo::Message::Response> object.
=head2 i
my $seconds = i {...};
my $seconds = i {...} 100;
i {...};
i {...} 100;
Measure time it took to execture block in floating seconds, with an optional
number of iterations, which defaults to C<1>.
Benchmark block and print the results to C<STDERR>, with an optional number of
iterations, which defaults to C<1>.
$ perl -Mojo -E 'say i { say g("mojolicio.us")->code }'
$ perl -Mojo -E 'i { say g("mojolicio.us")->code }'
=head2 j
Expand Down
20 changes: 13 additions & 7 deletions t/mojolicious/ojo.t
Expand Up @@ -9,7 +9,6 @@ BEGIN {

use Test::More;
use ojo;
use Time::HiRes 'usleep';

# Application
a('/' => sub { $_->render(data => $_->req->method . $_->req->body) })
Expand Down Expand Up @@ -50,11 +49,18 @@ is c(1, 2, 3)->join('-'), '1-2-3', 'right result';
# Dumper
is r([1, 2]), "[\n 1,\n 2\n]\n", 'right result';

# Timer
my $i = 0;
ok i { ++$i and usleep 0.025 * 1000000 } >= 0.025, 'got a time';
is $i, 1, 'block has been invoked once';
i { $i++ } 10;
is $i, 11, 'block has been invoked ten times';
# Benchmark
{
my $buffer = '';
open my $handle, '>', \$buffer;
local *STDERR = $handle;
my $i = 0;
i { ++$i };
is $i, 1, 'block has been invoked once';
like $buffer, qr/wallclock/, 'right output';
i { $i++ } 10;
is $i, 11, 'block has been invoked ten times';
like $buffer, qr/wallclock.*wallclock/s, 'right output';
}

done_testing();

0 comments on commit 1b90a7a

Please sign in to comment.