forked from creazyboyone/FastGithub
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathFlowAnalyzer.cs
104 lines (92 loc) · 3.07 KB
/
FlowAnalyzer.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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
using System;
using System.Collections.Concurrent;
using System.Linq;
using System.Threading;
namespace FastGithub.FlowAnalyze
{
sealed class FlowAnalyzer : IFlowAnalyzer
{
private const int INTERVAL_SECONDS = 5;
private readonly FlowQueues readQueues = new(INTERVAL_SECONDS);
private readonly FlowQueues writeQueues = new(INTERVAL_SECONDS);
/// <summary>
/// 收到数据
/// </summary>
/// <param name="flowType"></param>
/// <param name="length"></param>
public void OnFlow(FlowType flowType, int length)
{
if (flowType == FlowType.Read)
{
this.readQueues.OnFlow(length);
}
else
{
this.writeQueues.OnFlow(length);
}
}
/// <summary>
/// 获取流量分析
/// </summary>
/// <returns></returns>
public FlowStatistics GetFlowStatistics()
{
return new FlowStatistics
{
TotalRead = this.readQueues.TotalBytes,
TotalWrite = this.writeQueues.TotalBytes,
ReadRate = this.readQueues.GetRate(),
WriteRate = this.writeQueues.GetRate()
};
}
private class FlowQueues
{
private int cleaning = 0;
private long totalBytes = 0L;
private record QueueItem(long Ticks, int Length);
private readonly ConcurrentQueue<QueueItem> queues = new();
private readonly int intervalSeconds;
public long TotalBytes => this.totalBytes;
public FlowQueues(int intervalSeconds)
{
this.intervalSeconds = intervalSeconds;
}
public void OnFlow(int length)
{
Interlocked.Add(ref this.totalBytes, length);
this.CleanInvalidRecords();
this.queues.Enqueue(new QueueItem(Environment.TickCount64, length));
}
public double GetRate()
{
this.CleanInvalidRecords();
return (double)this.queues.Sum(item => item.Length) / this.intervalSeconds;
}
/// <summary>
/// 清除无效记录
/// </summary>
/// <returns></returns>
private bool CleanInvalidRecords()
{
if (Interlocked.CompareExchange(ref this.cleaning, 1, 0) != 0)
{
return false;
}
var ticks = Environment.TickCount64;
while (this.queues.TryPeek(out var item))
{
if (ticks - item.Ticks < this.intervalSeconds * 1000)
{
break;
}
else
{
this.queues.TryDequeue(out _);
}
}
Interlocked.Exchange(ref this.cleaning, 0);
return true;
}
}
}
}