请看看示例程序:
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 1func 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 3func 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}总结
以上是内存溢出为你收集整理的在swift中测量经过的时间全部内容,希望文章能够帮你解决在swift中测量经过的时间所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)