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

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.