2

I'm trying to find a way to tell how long its taken a function to execute in seconds. Currently I'm doing it this way:

 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)")

but every time I print out the seconds it always reads -1. I've looked into this question: elapsed time but I need the output to be in seconds. Any suggestions?

SwiftyJD
  • 5,257
  • 7
  • 41
  • 92
  • Are you looking for this? https://stackoverflow.com/questions/25006235/how-to-benchmark-swift-code-execution – Ahmad F Sep 30 '19 at 21:32
  • `compare` doesn't give you the difference between two times, it just tell someone you whether one is earlier/later than the other down to the given unit https://developer.apple.com/documentation/foundation/calendar/2293166-compare. The question you linked to has the answer you need; a `TimeInterval` is in seconds. just round the value to the nearest whole second if you don't want the fraction – Paulw11 Sep 30 '19 at 21:41
  • There are multiple ways to do this. Many users have posted timer methods, etc., however another option if you're using `URLSession` is this: https://developer.apple.com/documentation/foundation/urlsessiontaskmetrics# – Adrian Oct 01 '19 at 00:00

1 Answers1

1

Try this:

let start = Date.timeIntervalSinceReferenceDate

// do stuff

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

secondsElapsed will be a Double, but it will be in seconds. You can round it or truncate it if you want an Int.

Hope this helps!

Sam
  • 2,350
  • 1
  • 11
  • 22