Skip to content

Instantly share code, notes, and snippets.

@xqms
Created January 31, 2022 11:26
Show Gist options
  • Save xqms/890f6cff5a82cd21356ecd65e7652bfc to your computer and use it in GitHub Desktop.
Save xqms/890f6cff5a82cd21356ecd65e7652bfc to your computer and use it in GitHub Desktop.
Smooth rate limiter (C++)
// Smooth rate limiter based on token bucket
// Author: Max Schwarz <[email protected]>
#include "rate_limiter.h"
#include <ros/time.h>
class RateLimiter::Private
{
public:
Private(float rate)
: rate(rate)
{}
ros::Time lastTime{0};
float bucket = 0;
float rate;
};
RateLimiter::RateLimiter(float rate)
: m_d{std::make_unique<Private>(rate)}
{
}
RateLimiter::~RateLimiter()
{
}
bool RateLimiter::step()
{
ros::Time now = ros::Time::now();
if(m_d->lastTime == ros::Time(0))
{
m_d->lastTime = now;
return true;
}
else
{
// Basic token bucket algorithm for rate limiting
ros::Duration elapsed = now - m_d->lastTime;
m_d->lastTime = now;
m_d->bucket = std::min(2.0f,
m_d->bucket + static_cast<float>(elapsed.toSec()) * m_d->rate
);
if(m_d->bucket < 1.0f)
return false;
m_d->bucket -= 1.0f;
return true;
}
}
// Smooth rate limiter based on token bucket
// Author: Max Schwarz <[email protected]>
#ifndef RATE_LIMITER_H
#define RATE_LIMITER_H
#include <memory>
class RateLimiter
{
public:
explicit RateLimiter(float rate);
~RateLimiter();
//! Returns true if the event should be accepted
bool step();
private:
class Private;
std::unique_ptr<Private> m_d;
};
#endif
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment