22using System ;
33
44namespace fCraft {
5-
65 public sealed class PingList {
76
87 public struct PingEntry {
98 public DateTime TimeSent , TimeReceived ;
109 public ushort Data ;
10+ public double Latency { get {
11+ // Half, because received->reply time is actually twice time it takes to send data
12+ return ( TimeReceived - TimeSent ) . TotalMilliseconds * 0.5 ;
13+ } }
1114 }
15+
1216 public PingEntry [ ] Entries = new PingEntry [ 10 ] ;
1317
1418
@@ -30,9 +34,9 @@ public ushort NextTwoWayPingData() {
3034 }
3135
3236 ushort SetTwoWayPing ( int i , ushort prev ) {
33- Entries [ i ] . Data = ( ushort ) ( prev + 1 ) ;
34- Entries [ i ] . TimeSent = DateTime . UtcNow ;
35- return ( ushort ) ( prev + 1 ) ;
37+ Entries [ i ] . Data = ( ushort ) ( prev + 1 ) ;
38+ Entries [ i ] . TimeSent = DateTime . UtcNow ;
39+ return ( ushort ) ( prev + 1 ) ;
3640 }
3741
3842 public void Update ( ushort data ) {
@@ -44,39 +48,42 @@ public void Update(ushort data) {
4448 }
4549
4650
51+ /// <summary> Gets best ping in milliseconds, or 0 if no ping measures. </summary>
52+ public double BestPingMilliseconds ( ) {
53+ double totalMs = 100000000 ;
54+ foreach ( PingEntry ping in Entries ) {
55+ if ( ping . TimeSent . Ticks == 0 || ping . TimeReceived . Ticks == 0 ) continue ;
56+ totalMs = Math . Min ( totalMs , ping . Latency ) ;
57+ }
58+ return totalMs ;
59+ }
60+
4761 /// <summary> Gets average ping in milliseconds, or 0 if no ping measures. </summary>
4862 public double AveragePingMilliseconds ( ) {
4963 double totalMs = 0 ;
5064 int measures = 0 ;
51-
5265 foreach ( PingEntry ping in Entries ) {
5366 if ( ping . TimeSent . Ticks == 0 || ping . TimeReceived . Ticks == 0 ) continue ;
54-
55- // Half, because received->reply time is actually twice time it takes to send data
56- totalMs += ( ping . TimeReceived - ping . TimeSent ) . TotalMilliseconds * 0.5 ;
57- measures ++ ;
67+ totalMs += ping . Latency ; measures ++ ;
5868 }
5969 return measures == 0 ? 0 : ( totalMs / measures ) ;
6070 }
6171
62-
6372 /// <summary> Gets worst ping in milliseconds, or 0 if no ping measures. </summary>
6473 public double WorstPingMilliseconds ( ) {
6574 double totalMs = 0 ;
66-
6775 foreach ( PingEntry ping in Entries ) {
6876 if ( ping . TimeSent . Ticks == 0 || ping . TimeReceived . Ticks == 0 ) continue ;
69-
70- double ms = ( ping . TimeReceived - ping . TimeSent ) . TotalMilliseconds * 0.5 ;
71- totalMs = Math . Max ( totalMs , ms ) ;
77+ totalMs = Math . Max ( totalMs , ping . Latency ) ;
7278 }
7379 return totalMs ;
7480 }
7581
7682 public string Format ( ) {
77- return String . Format ( "Worst ping {0}ms, average {1}ms" ,
78- WorstPingMilliseconds ( ) . ToString ( "N0" ) ,
79- AveragePingMilliseconds ( ) . ToString ( "N0" ) ) ;
83+ return String . Format ( "Lowest ping {0}ms, average {1} ms, highest {2}ms" ,
84+ ( int ) BestPingMilliseconds ( ) ,
85+ ( int ) AveragePingMilliseconds ( ) ,
86+ ( int ) WorstPingMilliseconds ( ) ) ;
8087 }
8188 }
8289}
0 commit comments