-3

while practicing coding, I just caught up with question: which code will process faster in swift?

Is this one faster:

var aYear =  Int(readLine()!)! 

func isLeap(year: Int) 
{
  if aYear%400 == 0
  {
    print("YES")
  }
  else if aYear%4 == 0 && !(aYear%100 == 0)
  {
    print("YES")
  }
  else
  {
    print("NO")
  }  
}
isLeap(year: aYear) 

Or this one faster?

var aYear =  Int(readLine()!)!

func isLeap(year: Int) {

    var leap = "NO"

    if year % 4 == 0 {
        leap = "YES"
    }
    if year % 100 == 0 {
        leap = "NO"
    }
    if year % 400 == 0 {
        leap = "YES"
    }
    print(leap)
}
isLeap(year: aYear)

Thank you. Have a great day :)

Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116
nanorobo
  • 29
  • 2

1 Answers1

1

One way to check function performance is to this helper struct. Add the following to your project:

struct Benchmark {
    static func testElapsedTimeFor(_ title: String, operation: @escaping ()->()) {
        let startTime = CFAbsoluteTimeGetCurrent()
        operation()
        let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
        print("Time elapsed for \(title): \(timeElapsed) s.")
    }

    // If you would like to get the double instead
    static func testElapsedTimeFor(operation: @escaping ()->()) -> Double {
        let startTime = CFAbsoluteTimeGetCurrent()
        operation()
        let timeElapsed = CFAbsoluteTimeGetCurrent() - startTime
        return Double(timeElapsed)
    }
}

And use it like so:

Benchmark.testElapsedTimeFor("First Function") {
    self.isLeap(year: 2019)
}
DrewG23
  • 427
  • 3
  • 11