使用swift3制作下载速度测试应用程序的最佳方法是什么?

使用swift3制作下载速度测试应用程序的最佳方法是什么?,swift3,ios8.1,Swift3,Ios8.1,我正在使用下面从这个问题中截取的代码在我的应用程序中进行速度测试,但是当进行测试并与速度测试工具进行比较时,如果我的应用程序速度结果为1mbps,则我的应用程序的结果比speedTest.net的结果小一半。speedTest.net的结果为2mbps或更高 class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDataDelegate { override func viewDidLoad() {

我正在使用下面从这个问题中截取的代码在我的应用程序中进行速度测试,但是当进行测试并与速度测试工具进行比较时,如果我的应用程序速度结果为1mbps,则我的应用程序的结果比speedTest.net的结果小一半。speedTest.net的结果为2mbps或更高

class ViewController: UIViewController, NSURLSessionDelegate, NSURLSessionDataDelegate {

override func viewDidLoad() {
    super.viewDidLoad()

    testDownloadSpeedWithTimout(5.0) { (megabytesPerSecond, error) -> () in
        print("\(megabytesPerSecond); \(error)")
    }
}

var startTime: CFAbsoluteTime!
var stopTime: CFAbsoluteTime!
var bytesReceived: Int!
var speedTestCompletionHandler: ((megabytesPerSecond: Double?, error: NSError?) -> ())!

func testDownloadSpeedWithTimout(timeout: NSTimeInterval, completionHandler:(megabytesPerSecond: Double?, error: NSError?) -> ()) {
    let url = NSURL(string: "http://insert.your.site.here/yourfile")!

    startTime = CFAbsoluteTimeGetCurrent()
    stopTime = startTime
    bytesReceived = 0
    speedTestCompletionHandler = completionHandler

    let configuration = NSURLSessionConfiguration.ephemeralSessionConfiguration()
    configuration.timeoutIntervalForResource = timeout
    let session = NSURLSession(configuration: configuration, delegate: self, delegateQueue: nil)
    session.dataTaskWithURL(url).resume()
}

func URLSession(session: NSURLSession, dataTask: NSURLSessionDataTask, didReceiveData data: NSData) {
    bytesReceived! += data.length
    stopTime = CFAbsoluteTimeGetCurrent()
}

func URLSession(session: NSURLSession, task: NSURLSessionTask, didCompleteWithError error: NSError?) {
    let elapsed = stopTime - startTime
    guard elapsed != 0 && (error == nil || (error?.domain == NSURLErrorDomain && error?.code == NSURLErrorTimedOut)) else {
        speedTestCompletionHandler(megabytesPerSecond: nil, error: error)
        return
    }

    let speed = elapsed != 0 ? Double(bytesReceived) / elapsed / 1024.0 / 1024.0 : -1
    speedTestCompletionHandler(megabytesPerSecond: speed, error: nil)
}

}

我把我的文件放在不同的服务器上,每个服务器都会给我不同的结果,所以问题是速度结果取决于下载的服务器,解决方案是将文件放在多个服务器上,为客户端检测最佳服务器并从中下载

您的代码似乎使用单线程测试速度,这可能是它测量较低结果的主要原因之一

net和我们这样的大多数测试人员都使用多线程方法。这是一个更好的方法来估计互联网连接的容量

您可以在此处找到将执行多线程测量的iOS SDK:


多线程如何提高下载速度?CPU几乎从来都不是瓶颈。当然,我们在这里假设服务器会使链路饱和。你是对的,这与CPU瓶颈无关。它是关于单下载线程(或上传)无法使连接饱和的问题。这种情况在更高的速度下更为明显,例如,当100 Mbit连接可以被3个并行下载线程饱和时。1Gbit可能需要更多线程才能饱和。在我们的SDK中,每次达到额外的100 Mb/s增量时,我们都会添加一个额外的线程