File Coverage

blib/lib/Sub/Throttle.pm
Criterion Covered Total %
statement 26 26 100.0
branch 5 6 83.3
condition n/a
subroutine 7 7 100.0
pod 1 1 100.0
total 39 40 97.5


line stmt bran cond sub pod time code
1             package Sub::Throttle;
2              
3 1     1   37709 use strict;
  1         4  
  1         84  
4 1     1   5 use warnings;
  1         2  
  1         43  
5              
6 1     1   5 use Carp qw(croak);
  1         90  
  1         101  
7 1     1   16 use List::Util qw(max);
  1         2  
  1         147  
8 1     1   6 use Time::HiRes qw(time sleep);
  1         2  
  1         10  
9              
10             require Exporter;
11              
12             our @ISA = qw(Exporter);
13             our @EXPORT_OK = qw(throttle);
14             our %EXPORT_TAGS = (
15             all => [ @EXPORT_OK ],
16             );
17             our @EXPORT = ();
18             our $VERSION = '0.02';
19              
20             sub throttle {
21 4 50   4 1 21 croak "too few arguments to throttle\n"
22             if @_ < 2;
23 4         10 my ($load, $func, @args) = @_;
24 4         8 my @ret;
25 4         14 my $start = time;
26 4 100       13 if (wantarray) {
27 2         8 @ret = $func->(@args);
28             } else {
29 2         7 $ret[0] = $func->(@args);
30             }
31 4         1000236 sleep(_sleep_secs($load, time - $start));
32 4 100       278 wantarray ? @ret : $ret[0];
33             }
34              
35             sub _sleep_secs {
36 8     8   24 my ($load, $elapsed) = @_;
37 8         3001374 max($elapsed, 0) * (1 - $load) / $load;
38             }
39              
40             1;
41             =head1 NAME
42              
43             Sub::Throttle - Throttle load of perl function
44              
45             =head1 SYNOPSIS
46              
47             use Sub::Throttle qw(throttle);
48            
49             my $load = 0.1;
50            
51             throttle($load, sub { ... });
52             throttle($load, \&subref, @args);
53              
54             =head1 DESCRIPTION
55              
56             Throttles the load of perl function by calling L.
57              
58             =head1 METHODS
59              
60             =head2 throttle($load, $subref [, @subargs])
61              
62             Calls L after executing $subref with given @subargs so that the ratio of execution time becomes equal to $load.
63              
64             =head1 AUTHOR
65              
66             Kazuho Oku Ekazuhooku at gmail.comE
67              
68             =head1 COPYRIGHT AND LICENSE
69              
70             Copyright (C) 2008 by Cybozu Labs, Inc.
71              
72             This library is free software; you can redistribute it and/or modify
73             it under the same terms as Perl itself, either Perl version 5.8.6 or,
74             at your option, any later version of Perl 5 you may have available.
75              
76             =cut