Search Unity

Question How to check (reliable) Internet connection speed?

Discussion in 'Scripting' started by danielesuppo, Dec 6, 2022.

  1. danielesuppo

    danielesuppo

    Joined:
    Oct 20, 2015
    Posts:
    331
    Hello,
    I should check in a reliable way the Internet connection speed in my app.
    I've tried a couple of solutions, that I write below, but none of them seem to return at least an approximate value of the real speed of my connection (around 30Mb per second, with SpeedTest)

    Solution 1
    Code (CSharp):
    1. public double GetInternetSpeed()
    2.         {
    3.             // Create Object Of WebClient
    4.             System.Net.WebClient wc = new System.Net.WebClient();
    5.  
    6.             //DateTime Variable To Store Download Start Time.
    7.             DateTime dt1 = DateTime.UtcNow;
    8.  
    9.             //Number Of Bytes Downloaded Are Stored In ‘data’
    10.             byte[] data = wc.DownloadData(endpoint);
    11.  
    12.             //DateTime Variable To Store Download End Time.
    13.             DateTime dt2 = DateTime.UtcNow;
    14.  
    15.             //To Calculate Speed in Kb Divide Value Of data by 1024 And Then by End Time Subtract Start Time To Know Download Per Second.
    16.             return Math.Round((data.Length / 1024) / (dt2 - dt1).TotalSeconds, 2);
    17.         }
    Result: around 100 (???)

    Solution 2
    Code (CSharp):
    1. public async Task<int> GetInternetSpeedAsync(CancellationToken ct = default)
    2.         {
    3.                  
    4.             const double kb = 1024;
    5.  
    6.             // do not use compression
    7.             using var client = new HttpClient();
    8.  
    9.             int numberOfBytesRead = 0;
    10.  
    11.             var buffer = new byte[10240].AsMemory();
    12.  
    13.             // create request
    14.             var stream = await client.GetStreamAsync("https://www.google.it");
    15.  
    16.             // start timer
    17.             DateTime dt1 = DateTime.UtcNow;
    18.  
    19.             // download stuff
    20.             while (true)
    21.             {
    22.                 var i = await stream.ReadAsync(buffer, ct);
    23.                 if (i < 1)
    24.                     break;
    25.  
    26.                 numberOfBytesRead += i;
    27.             }
    28.  
    29.             // end timer
    30.             DateTime dt2 = DateTime.UtcNow;
    31.  
    32.             double kilobytes = numberOfBytesRead / kb;
    33.             double time = (dt2 - dt1).TotalSeconds;
    34.             // speed in Kb per Second.
    35.             Debug.Log("speed:" + (int)(kilobytes / time));
    36.             return (int)(kilobytes / time);
    37.         }
    Result: around 75 (????)

    It seem to me quite weird that these functions return values way too lower than the actual speed.
    Maybe I'm missing something?
    Maybe is there a better solution?
    Many thanks!
     
  2. Kurt-Dekker

    Kurt-Dekker

    Joined:
    Mar 16, 2013
    Posts:
    38,749
    I don't think this is even possible... you could hit a speedtest service but even those are questionable in actual accuracy.
     
    Bunny83 likes this.
  3. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,011
    There are several things wrong with your implementation. First of all as everybody should know, HTTP, especially HTTPS is notoriously slow when it comes to establishing a connection. There are several handshakes involved before even a single byte of data is transferred. On top of that the request as well as response header contains significant amount of data that you did not consider. This is even more important when the actual data payload that you're loading is small. SpeedTests deliberately sending out hundreds of MB if not GB to eliminate any potential slow down from establishing the connection.

    Next DateTime is not very accurate to measure very small time spans. You should use the Stopwatch class for things like that.

    I'm pretty sure more speed test websites would use a WebSocket connection to carry out the actual bandwidth test as well as the seperate ping / RTT measurement.

    Finally the term "speed" could mean different things. Of course speed is generally measured in "units per time" and we're interested in how many bytes can be transferred in a certain timeframe. Though this has to be broken up into two parts: bandwidth and round trip time. Because you can have a "bad connection" because you try to reach a server on the other side of the planet and you may have a "ping" of 150ms, but you can still have a huge bandwidth. So the connection is fast in terms of how much data it can transfer per unit time, but it is slow when you look at the response time. The same thing could be the other way round. You may sit right next to a data center and have a ping under 1ms. Though if your connection bandwidth is not that high, you won't get much data through it, even though the first bit arrives very fast.

    In extreme cases you could have latencies of 2 seconds, but still have a huge through put. That's why all those speed test websites measure both, the bandwidth (usually seperately for up- and download) as well as the latency. Gamers usually care less about the bandwidth (unless you want to install a steam game) but more about the latency. Someone playing quake with a dailup modem may have a better ping in Quake than someone with a 1GBit/s connection that is on the other side of the world.

    So in short:
    You should first think about what exactly you try to measure and if it's actually worth it. If you decide it's worth it and necessary, there are those points:

    • Do not use HTTP, let alone HTTPS, for speed tests if you can avoid it.
    • Do not abuse public services like google for such tests because this can actually get you into trouble as it's against their terms of services.
    • Host your own server somewhere (in a data center or whereever you like) and use that to do the speed testing
    • Unless restricted by the platform (like a WebGL build for example) avoid SSL/TLS over TCP and use UDP instead if possible.
    • Send enough data to actually smooth out any short term influences and setup delays.
    For most server related stuff I usually use my Raspberry PI. It runs several servers here at home. I also have a dynamic DNS name, so I can reach it from anywhere. Though for speed tests, you really want to host a server in a proper data center. Though, note that internet traffic is not for free. Even though the majority of end users have a flat-rate and "unlimited" traffic, in reality every byte that is transported through the internet costs money and has to be paid. ISPs work like insurance companies. They rely on the fact, that only a small percentage of users actually use their connection to its limits 24/7. Most people are on idle 99% of the time. When you host a server in a datacenter, you have to pay for the power consumption as well as the used traffic, in and out.
     
    kasym_ likes this.
  4. Bunny83

    Bunny83

    Joined:
    Oct 18, 2010
    Posts:
    4,011
    ps:
    I'm not sure why or for what purpose you actually need your internet connection. Usually you want to talk to your server anyways. So checking against some other completely unrelated website just makes no sense. You could have a good connection to server A but a bad one to server B. So knowing you're good on A doesn't help you judging the connection quality to B.

    A cheap solution could be to use something like pastebin and use a relatively large file, say 100MB and try downloading this. Though be warned: If you're developing a mobile app, the user may be on a limited plan and they would be super pissed if you burned up all the traffic they had for nothing.

    It would help if you could clarify why you need to know the connection speed.
     
  5. Unity_shweta

    Unity_shweta

    Joined:
    Nov 24, 2023
    Posts:
    1
    With the help of FiberTest, you can easily check your internet speed anytime, anywhere. Additionally, for a global perspective on internet speeds, you can explore Global Broadband Live, where you can find country-wise live average download and upload speeds. These platforms provide convenient ways to assess and compare internet speeds on a local and global scale