在swift中测量经过的时间

前端之家收集整理的这篇文章主要介绍了在swift中测量经过的时间前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我们如何测量在Swift中运行函数所用的时间?我试图显示已过去的时间,如下所示:“弹出时间为.05秒”。看到 in Java,我们可以使用System.nanoTime(),有没有任何等效的方法方法可用在Swift中实现这个?

请看看示例程序:

func isPrime(var number:Int) ->Bool {
    var i = 0;
    for i=2; i<number; i++ {
        if(number % i == 0 && i != 0) {
            return false;
        }
    }
    return true;
}

var number = 5915587277;

if(isPrime(number)) {
    println("Prime number");
} else {
    println("NOT a prime number");
}
这里有一个Swift函数,我写了测量 Project Euler问题在Swift

它使用NSDate

// Swift 1
func evaluateProblem(problemNumber: Int,problemBlock: () -> Int) -> Answer
{
    println("Evaluating problem \(problemNumber)");

    let start = NSDate(); // <<<<<<<<<< Start time
    let myGuess = problemBlock();
    let end = NSDate();   // <<<<<<<<<<   end time

    let theAnswer = self.checkAnswer(answerNum: "\(problemNumber)",guess: myGuess);

    let timeInterval: Double = end.timeIntervalSinceDate(start); // <<<<< Difference in seconds (double)

    println("Time to evaluate problem \(problemNumber): \(timeInterval) seconds");
    return theAnswer;
}

更新

从Swift 3开始,现在有一个版本的中央调度“swifitfied”。所以新的正确答案大概是使用DispatchTime API

我的功能将看起来像(没有实际测试或任何东西):

// Swift 3
func evaluateProblem(problemNumber: Int,problemBlock: () -> Int) -> Answer
{
    print("Evaluating problem \(problemNumber)")

    let start = DispatchTime.now() // <<<<<<<<<< Start time
    let myGuess = problemBlock()
    let end = DispatchTime.now()   // <<<<<<<<<<   end time

    let theAnswer = self.checkAnswer(answerNum: "\(problemNumber)",guess: myGuess)

    let nanoTime = end.uptimeNanoseconds - start.uptimeNanoseconds // <<<<< Difference in nano seconds (UInt64)
    let timeInterval = Double(nanoTime) / 1_000_000_000 // Technically could overflow for long running tests

    print("Time to evaluate problem \(problemNumber): \(timeInterval) seconds")
    return theAnswer
}
原文链接:https://www.f2er.com/swift/321076.html

猜你在找的Swift相关文章