计算连接/下载速度 [英] Calculating Connection/Download Speed

查看:125
本文介绍了计算连接/下载速度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个客户端和服务器程序(都在Obj-C中),我使用程序在两个设备之间传输文件。

I have a client and server program (both in Obj-C) and I am transferring files between two devices using the programs.

传输正常,但我想向用户显示他们正在得到的传输速率。

The transferring is working fine, but I would like to display to the user what transfer rate they are getting.

所以我知道文件的总大小,以及文件的传输量,有没有办法从这些信息中找出传输速率,如果没有,我需要什么信息来计算传输速率?

So I know the total size of the file, and how much of the file has been transferred, is there a way to figure out the transfer rate from this information, and if not, what information do I need to calculate the transfer rate?

感谢

推荐答案

一旦开始下载,捕获当前系统时间并将其存储为开始时间。然后,在传输过程中任何时候计算传输速度所需要做的就是再次查看系统时间,并使用它作为当前时间来计算到目前为止花费的总时间:

As soon as you start the download, capture the current system time and store it as the "start time". Then, all you need to do to calculate transfer speed at any point during the transfer is to look at the system time again and use it as the "current time" to calculate the total time spent so far:

transfer_speed = bytes_transferred / ( current_time - start_time)

你可能想要使用秒或毫秒的精度与时间,当然可以乘以8,如果你想比特/秒。

You probably want to use second or millisecond accuracy with the times, and of course can multiply the result by 8 if you want bits/second.

你使用Cocoa,你可以使用NSDate类来获取时间戳。例如,在开始传输时使用以下命令:

Since you're using Cocoa, you could use the NSDate class to get the timestamps. For example, use the following when you start the transfer:

NSTimeInterval start = [NSDate timeIntervalSinceReferenceDate];

然后使用以下方式定期检查转移率:

Then periodically check the transfer rate by using:

double speed = bytesTransferred / ([NSDate timeIntervalSinceReferenceDate] - start);

这篇关于计算连接/下载速度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆