Question about Ping (or RTT) and Packet Loss

I have a game where I want to make the current Ping available to the user, so I make some requests and store them in a list, old requests are removed.

My code is similar to this one, I made some simplifications so you don’t get bored, the problem here is not about the code, but how it should work:

public class Metrics : MonoBehaviour
{
    public int pingAverage = -1;

    void Start()
    {
        StartCoroutine(Refreshing());
    }

    IEnumerator Refreshing()
    {
        // Remember 10 pings.
        const int WINDOW_SIZE = 10;

        int sum = 0;
        LinkedList<int> pings = new LinkedList<int>();

        while (true)
        {
            // Simplified. Low precision.
            float start = Time.timeSinceLevelLoad;
            yield return conn.Request();
            float end = Time.timeSinceLevelLoad;

            if (!conn.err)
            {
                int ping = (end - start) * 1000;

                sum += ping;
                pings.AddLast(ping);

                if (pings.Count > WINDOW_SIZE)
                {
                    int first = pings.First.Value;

                    pings.RemoveFirst();
                    sum -= first;
                }

                pingAverage = sum / pings.Count;
            }
            else
            {
                // What i do here?
            }

            yield return new WaitForSeconds(0.5f);
        }
    }
}

With this code, if there are errors, it may be that the average ping is 10 ms, but 10 minutes ago that no measurements were made. I remember that for example League of Legends set Ping at 500 ms when the game was disconnected.

*Note that error checking sounds like a packet loss to me.

In your code there’s a reference to tcp. Are you trying to monitor TCP packet loss? If so it sounds a bit confusing as packet loss in TCP is handled by the protocol itself.

Also what is the error condition you’re checking in the code?

1 Like

I edited, tcp was just any name.