Reputation: 67
could someone help me a little? I'm downloading files and I'm able to get the actual download speed. but I want to change the UNIT from KB/sec to MB/sec if the speed is greater than 1mbps
How do I know if is greater than 1mbps so that I the UNIT will change as well
Here's my current code.
I'm running this in a loop.
for (int i = 0; i < totalCount; i++)
{
string downloadUrl= LB.Items[i].toString();
double currentSize = TotalFileSize; //882672
string UNIT = "KB/s";
DateTime startTime = DateTime.Now;
await ProgressUpdate(downloadUrl, cts.Token); //the actual download
DateTime endTime = DateTime.Now;
double t = Math.Round(currentSize / 1024 / (endTime - startTime).TotalSeconds);
var downloadSpeed = (string.Format("Download Speed: {0}{1}", t, UNIT));
Thank you.
Upvotes: 0
Views: 967
Reputation: 16049
You can use a little Helper, for example:
var downloadSpeed = FormatSpeed(TotalFileSize, (endTime - startTime).TotalSeconds);
string FormatSpeed( double size, double tspan )
{
string message = "Download Speed: {0:N0} {1}";
if( size/tspan > 1024 * 1024 ) // MB
{
return string.Format(message, size/(1024*1204)/tspan, "MB/s");
}else if( size/tspan > 1024 ) // KB
{
return string.Format(message, size/(1024)/tspan, "KB/s");
}
else
{
return string.Format(message, size/tspan, "B/s");
}
}
See it run: https://dotnetfiddle.net/MjUW2M
Output:
Download Speed: 10 B/s
Download Speed: 100 B/s
Download Speed: 200 B/s
Download Speed: 100 KB/s
Download Speed: 83 MB/s
Download Speed: 9 MB/s
Or a slight variation: https://dotnetfiddle.net/aqanaT
string FormatSpeed( double size, double tspan )
{
string message = "Download Speed: ";
if( size/tspan > 1024 * 1024 ) // MB
{
return string.Format(message + "{0:N1} {1}", size/(1024*1204)/tspan, "MB/s");
}else if( size/tspan > 1024 ) // KB
{
return string.Format(message + "{0:N0} {1}", size/1024/tspan, "KB/s");
}
else
{
return string.Format(message + "{0:N1} {1}", size/1024/tspan, "KB/s");
}
Output:
Download Speed: 0.0 KB/s
Download Speed: 0.1 KB/s
Download Speed: 0.2 KB/s
Download Speed: 100 KB/s
Download Speed: 83.1 MB/s
Download Speed: 8.5 MB/s
Upvotes: 1