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

soham picture soham · Nov 28, 2012 · Viewed 35.9k times · Source

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.

Answer

user166390 picture user166390 · Nov 28, 2012

Here is a quick snippet of code from LINQPad. It uses a very simple moving average. It shows "accurate speeds" using "Speedtest.net". Things to keep in mind are Kbps is in bits and HTTP data is often compressed so the "downloaded bytes" will be significantly smaller for highly compressible data. Also, don't forget that any old process might be doing any old thing on the internet these days (without stricter firewall settings) ..

I like flindenberg's answer (don't change the accept), and I noticed that some polling periods would return "0" that aligns with his/her conclusions.

Use at your own peril.

void Main()
{
    var nics = System.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces();
    // Select desired NIC
    var nic = nics.Single(n => n.Name == "Local Area Connection");
    var reads = Enumerable.Empty<double>();
    var sw = new Stopwatch();
    var lastBr = nic.GetIPv4Statistics().BytesReceived;
    for (var i = 0; i < 1000; i++) {

        sw.Restart();
        Thread.Sleep(100);
        var elapsed = sw.Elapsed.TotalSeconds;
        var br = nic.GetIPv4Statistics().BytesReceived;

        var local = (br - lastBr) / elapsed;
        lastBr = br;

        // Keep last 20, ~2 seconds
        reads = new [] { local }.Concat(reads).Take(20);

        if (i % 10 == 0) { // ~1 second
            var bSec = reads.Sum() / reads.Count();
            var kbs = (bSec * 8) / 1024; 
            Console.WriteLine("Kb/s ~ " + kbs);
        }
    }
}