简体   繁体   中英

How do I detect average download speed?

So I want to make an Speedtest alike, I am downloading an 100MB file (is it too much to test average download speed?). I am getting an huge number and I can't calculate the average download speed like that...

Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    If Downloading Then Exit Sub
    Downloading = True

    Dim wc As New WebClient
    AddHandler wc.DownloadProgressChanged, AddressOf wc_ProgressChanged
    AddHandler wc.DownloadFileCompleted, AddressOf wc_DownloadDone

    wc.DownloadFileAsync(New Uri("http://speedtest.ftp.otenet.gr/files/test100Mb.db"), tmp, Stopwatch.StartNew)
End Sub

Private Sub wc_DownloadDone(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs)
    Downloading = False
End Sub

Private Sub wc_ProgressChanged(sender As Object, e As DownloadProgressChangedEventArgs)
    Me.Label2.Text = (e.BytesReceived / (DirectCast(e.UserState, Stopwatch).ElapsedMilliseconds / 1000.0#)).ToString("#")
End Sub

Offtopic: Is there also a way to calculate the average upload speed?

The huge number you are getting is bytes/second. You need to divide it by 1024 to get Kilobytes/second or (1024 * 1024) to get Megabytes/second

Me.Label2.Text = (e.BytesReceived / (DirectCast(e.UserState, Stopwatch).ElapsedMilliseconds / 1000.0#) / (1024 * 1024)).ToString("#")

To get Megabits per second like speed test does you need to also multiply by 8

Me.Label2.Text = (e.BytesReceived / (DirectCast(e.UserState, Stopwatch).ElapsedMilliseconds / 1000.0#) / (1024 * 1024) * 8).ToString("#")

Depends on how accurate you want the speedtest to be, the larger the file the more accurate it is. But this can be a big annoyance/data hog for the user.

The big number appears because it's in bytes, to get Mb/s you need to do Your result / 1024^2 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM