Introduction to Swift

Apr 24 2024 · Swift 5.10, iOS 17, Xcode 15

Lesson 04: Problem Solving

Measuring Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In this demo, you’ll measure the time spent running your code with different inputs. Then, you’ll change your solution to use a more optimized approach.

calculateSum(minValue: 0, maxValue: 100_000)
calculateSum(minValue: 0, maxValue: 1_000_000)
calculateSum(minValue: 0, maxValue: 100_000_000)
func calculateSumOptimized(minValue: Int, maxValue: Int) -> Int {

}
var sum = 0
sum = (minValue + maxValue) / 2
sum *= maxValue - minValue + 1

return sum
func calculateSum_optimized(minValue: Int, maxValue: Int) -> Int {
  var sum = 0
  let timeMeasure = ContinuousClock().measure {
    sum = (minValue + maxValue) / 2
    sum *= (maxValue - minValue + 1)
  }

  print("\(timeMeasure) for result \(sum)")
  return sum
}
calculateSum_optimized(minValue: 0, maxValue: 10)
calculateSum_optimized(minValue: 0, maxValue: 100)

calculateSum_optimized(minValue: 0, maxValue: 100_000)
calculateSum_optimized(minValue: 0, maxValue: 1_000_000)
calculateSum_optimized(minValue: 0, maxValue: 100_000_000)
See forum comments
Cinema mode Download course materials from Github
Previous: Measuring Efficiency Next: Guarding Against Bad Input