This repository has been archived by the owner on Feb 3, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 8
/
MetricsCollector.cs
71 lines (63 loc) · 2.02 KB
/
MetricsCollector.cs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
using System;
using System.Linq;
namespace FhirLoader
{
///<summary>
/// Simple class for collecting events.
/// Contains a circular buffer used to bin events.
///</summary>
public class MetricsCollector
{
private readonly object _metricsLock = new object();
private int _bins = 0;
private int _resolutionMs = 1000;
private int _startBin = 0;
private int _maxBinIndex = 0;
private DateTime? _startTime = null;
private long[] _counts;
///<summary>
/// Constructor
///</summary>
public MetricsCollector(int bins = 30, int resolutionMs = 1000)
{
_bins = bins;
_counts = new long[bins];
_resolutionMs = resolutionMs;
}
///<summary>
/// Register event at specific time
///</summary>
public void Collect(DateTime eventTime)
{
lock (_metricsLock)
{
if (_startTime is null)
{
_startTime = DateTime.Now;
}
int binIndex = (int)((eventTime - _startTime.Value).TotalMilliseconds / _resolutionMs);
while (binIndex >= _bins)
{
_counts[_startBin] = 0;
_startBin = (_startBin + 1) % _bins;
_startTime += TimeSpan.FromMilliseconds(_resolutionMs);
binIndex--;
}
_counts[(binIndex + _startBin) % _bins]++;
// We keep track of this to make sure that in the warm up, we take the average only of bins used
_maxBinIndex = binIndex;
}
}
///<summary>
/// Return events per second
///</summary>
public double EventsPerSecond {
get {
lock (_metricsLock)
{
return (double)_counts.Sum() / (_resolutionMs * (_maxBinIndex + 1) / 1000.0);
}
}
}
}
}