Token bucket rate limiter using Stopwatch
C#
using System;
using System.Diagnostics;
sealed class TokenBucket
{
private readonly double _rate, _burst;
private double _tokens;
private long _last = Stopwatch.GetTimestamp();
public TokenBucket(double rate, double burst) { _rate = rate; _burst = burst; _tokens = burst; }
public bool TryTake(double cost = 1)
{
long now = Stopwatch.GetTimestamp();
_tokens = Math.Min(_burst, _tokens + (now - _last) / (double)Stopwatch.Frequency * _rate);
_last = now;
if (_tokens < cost) return false;
_tokens -= cost;
return true;
}
}