Search code examples
c#.netnetwork-interface

How to get accurate download/upload speed in C#.NET?


I want to get accurate download/upload speed through a Network Interface using C# .NET I know that it can be calculated using GetIPv4Statistics().BytesReceived and putting the Thread to sleep for sometime. But it's not giving the output what I am getting in my browser.


Solution

  • By looking at another answer to a question you posted in NetworkInterface.GetIPv4Statistics().BytesReceived - What does it return? I believe the issue might be that you are using to small intervals. I believe the counter only counts whole packages, and if you for example are downloading a file the packages might get as big as 64 KB (65,535 bytes, IPv4 max package size) which is quite a lot if your maximum download throughput is 60 KB/s and you are measuring 200 ms intervals.

    Given that your speed is 60 KB/s I would have set the running time to 10 seconds to get at least 9 packages per average. If you are writing it for all kinds of connections I would recommend you make the solution dynamic, ie if the speed is high you can easily decrease the averaging interval but in the case of slow connections you must increase the averaging interval.

    Either do as @pst recommends by having a moving average or simply increase the sleep up to maybe 1 second.

    And be sure to divide by the actual time taken rather than the time passed to Thread.Sleep().

    Additional thought on intervals

    My process would be something like this, measure for 5 second and gather data, ie bytes recieved as well as the number of packets.

    var timePerPacket = 5000 / nrOfPackets; // Time per package in ms
    var intervalTime = Math.Max(d, Math.Pow(2,(Math.Log10(timePerPacket)))*100);
    

    This will cause the interval to increase slowly from about several tens of ms up to the time per packet. That way we always get at least (on average) one package per interval and we will not go nuts if we are on a 10 Gbps connection. The important part is that the measuring time should not be linear to the amount of data received.