Managed to increase speed by performing binary search on @keys. My module is now only about 40% slower when max_items=100 and 4x slower when max_items=1000.
package Data::Throttler_CHI; use strict; use warnings; use List::BinarySearch::XS qw(binsearch_pos); sub new { my ($package, %args) = @_; bless \%args, $package; } my $counter = 0; sub try_push { my $self = shift; my $now = time(); $counter++; $counter = 0 if $counter == 2e31; # wraparound 32bit int $self->{cache}->set(sprintf("%010d %d", $now, $counter), 1, $self- +>{interval}); # Y2286! # we assume the driver returns keys in insert order, to avoid havi +ng to sort() #my @keys = sort $self->{cache}->get_keys; my @keys = $self->{cache}->get_keys; return 1 if @keys <= $self->{max_items}; my $time_expired = $now - $self->{interval}; my $pos_not_expired = binsearch_pos { no warnings 'numeric'; $a <= +> $b } $time_expired, @keys; $self->{cache}->purge if rand() < 0.01; (@keys - $pos_not_expired) <= $self->{max_items} ? 1:0; } 1;
In reply to Re: Optimizing a CHI-based data throttler
by perlancar
in thread Optimizing a CHI-based data throttler
by perlancar
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |