How long a Function takes to execute ?

Replies

If you just want to measure the time consumed for executing a function, you can write something like this:


func someFunc() {
    //Time consuming something...
    var a = ""
    for i in 0..<1_000_000 {
        a += String(i)
    }
    _ = a
}


let start = Date()
someFunc()
let end = Date()
let consumedTime = end.timeIntervalSince(start)
print(consumedTime) //->0.06515908241271973


If you need something more, you may need to be more specific:

- What do you want? Do you want any sort of UI update?

- What does your function do?

Thanks for the reply. I mean generally measure any function.

Did you look at Instruments, to measure how much time you spend in a function ? That's the best way to optimize code, as it shows where you effectively spend most time.