Question

I'm making some changes for Open Hardware Monitor. I will add the network adapter download and upload speed. But when I calculate the download speed I get a wrong calculation.

I can't use a timer to calculate the correct download speed because of the auto update in OHM. In the source here you can see how I calculate the download speed (in Mb/s).

In the construct of the class i do:

IPv4InterfaceStatistics interfaceStats = netInterfaces.GetIPv4Statistics();

bytesSent = interfaceStats.BytesSent;
bytesReceived = interfaceStats.BytesReceived;

stopWatch = new Stopwatch();
stopWatch.Start();

When the update method is called (in some random times) I do this:

IPv4InterfaceStatistics interfaceStats = netInterfaces.GetIPv4Statistics();

stopWatch.Stop();
long time = stopWatch.ElapsedMilliseconds;

if (time != 0)
{
    long bytes = interfaceStats.BytesSent;
    long bytesCalc = ((bytes - bytesSent)*8);

    usedDownloadSpeed.Value = ((bytesCalc / time) * 1000)/1024;
    bytesSent = bytes;                 
}

Hope someone can see my issue?

enter image description here

Added screenshot

Was it helpful?

Solution

There where a few conversion issues with my previous code. Now I have this source and it works. Tnx all for answering.

    interfaceStats = netInterfaces.GetIPv4Statistics();

        //Calculate download speed
        downloadSpeed.Value = Convert.ToInt32(interfaceStats.BytesReceived - bytesPreviousReceived) / 1024F;

        bytesPreviousReceived = interfaceStats.BytesReceived;

OTHER TIPS

The following changes should help...

speed = netInterfaces.Speed / 1048576L;

If I recall correctly, the Speed property is a long and when you divide it by an int, you end up with a truncated result. Which brings us to a similar set of changes in your other calculation...

usedDownloadSpeed.Value = ((bytesCalc / time) * 1000L)/1024L;

... assuming that usedDownloadSpeed.Value is also a long to make sure you're not getting any truncated values with implicit conversion of your results or calculations. If you want to be doubly sure you have the casting correctly, use Convert.ToInt64().

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top