我正在尝试将循环(正在发送消息)限制为每秒特定数量的消息。_throttle
是每秒的消息数。
我的初始算法如下所示,但延迟并不平滑。
我可以做哪些改进来消除相当颠簸的延迟和消息突发。
我玩过滴答声和最大间隔,但入站计数如此之大,难以弥补。在我的实现中关闭油门可以达到的最大速率约为 15000/秒。我正在测试每秒 300 到 1000 之间的速率,所以我试图减慢它的速度。
private class ThrottleCalculator
{
private readonly int _throttle;
private DateTime _lastCalculation = DateTime.Now;
private int _count = 0;
private int _interval = 0;
public ThrottleCalculator(int throttle)
{
this._throttle = throttle;
}
public async Task CalculateThrottle()
{
this._count += 1;
var elapsed = DateTime.Now.Subtract(this._lastCalculation).TotalMilliseconds;
var tick = 50;
if (elapsed > tick)
{
this._lastCalculation = DateTime.Now;
int projection = this._count * (1000 / tick);
var errorTerm = this._throttle - projection;
this._interval = this._interval - errorTerm;
if (this._interval < 0)
this._interval = 0;
// this is often several thousand, so I have to limit.
if (this._interval > 100)
this._interval = 100;
await Task.Delay(this._interval);
this._count = 0;
}
}
}
使用它的代码每次迭代都会调用它。
var throttle = new ThrottleCalculator(600); // 600/s
while (message = getMessage())
{
... // do stuff with message.
if (throttle != null)
await throttle.CalculateThrottle();