【问题标题】:Find how long it takes a function to execute in seconds [duplicate]找出在几秒钟内执行一个函数需要多长时间[重复]
【发布时间】:2020-01-30 04:43:37
【问题描述】:

我正在尝试找到一种方法来判断它在几秒钟内执行一个函数需要多长时间。目前我正在这样做:

 let startDate = Date()
    let endDate = Date()
    let calendar = Calendar.current
    let dateComponents = calendar.compare(startDate, to: endDate, toGranularity: .second)
    let seconds = dateComponents.rawValue
    print("Seconds: \(seconds)")

但每次我打印出秒数时,它总是显示为 -1。我已经研究过这个问题:elapsed time 但我需要输出以秒为单位。有什么建议吗?

【问题讨论】:

标签: ios swift date time


【解决方案1】:

试试这个:

let start = Date.timeIntervalSinceReferenceDate

// do stuff

let end = Date.timeIntervalSinceReferenceDate
let secondsElapsed = end - start

secondsElapsed 将是 Double,但会以秒为单位。如果你想要Int,你可以舍入或截断它。

希望这会有所帮助!

【讨论】:

    猜你喜欢
    • 2017-04-17
    • 2014-07-10
    • 1970-01-01
    • 2019-04-21
    • 2014-12-06
    • 1970-01-01
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    相关资源
    最近更新 更多