Slash Boxes
NOTE: use Perl; is on undef hiatus. You can read content, but you can't post it. More info will be forthcoming forthcomingly.

All the Perl that's Practical to Extract and Report

use Perl Log In

Log In

[ Create a new account ]

acme (189)

  (email not shown publicly)

Leon Brocard (aka acme) is an orange-loving Perl eurohacker with many varied contributions to the Perl community, including the GraphViz module on the CPAN. YAPC::Europe was all his fault. He is still looking for a Perl Monger group he can start which begins with the letter 'D'.

Journal of acme (189)

Tuesday May 22, 2007
05:47 AM

Leaky buckets

[ #33329 ]

My buckets are leaky! If you ever have to do anything like rate limiting or throttling you should look at the token bucket algorithm. Handily CPAN has Algorithm::TokenBucket (which is similar) to make it easy for you. I recently wanted to throttle Net::SFTP::Foreign and ended up with something like this:

use Algorithm::TokenBucket;
use Net::SFTP::Foreign::Compat;
use Time::HiRes qw(sleep);

my $mbps   = 0.5;
my $bps    = $mbps * 1024 * 1024 / 8;
my $bucket = Algorithm::TokenBucket->new( $bps, 32768 );


        my $last_offset = 0;
            sub {
                my ( $sftp, $data, $offset, $size ) = @_;
                my $bytes = $offset - $last_offset;
                $last_offset = $offset;
                sleep 0.01 until $bucket->conform($bytes);

The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way.
More | Login | Reply
Loading... please wait.