0
0
Swiftprogramming~20 mins

Performance testing with measure blocks in Swift - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Performance Testing Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of measure block timing in XCTest

What will be printed by this Swift XCTest performance test?

Swift
func testPerformanceExample() {
    measure {
        var sum = 0
        for i in 1...1000 {
            sum += i
        }
        print(sum)
    }
}
A500500
B1000
C0
DCompilation error
Attempts:
2 left
💡 Hint

Think about the sum of numbers from 1 to 1000.

🧠 Conceptual
intermediate
1:30remaining
Purpose of measure block in XCTest

What is the main purpose of using a measure block in XCTest performance tests?

ATo test the correctness of the output values
BTo check if the code compiles without errors
CTo measure the average execution time of the code inside the block
DTo run the code only once for debugging
Attempts:
2 left
💡 Hint

Think about what performance testing means.

🔧 Debug
advanced
2:00remaining
Identify the error in this performance test

What error will this Swift performance test cause?

Swift
func testPerformance() {
    measure {
        var array = [1, 2, 3]
        array.append(4)
    }
}
ACompilation error: Cannot use mutating method on immutable value
BRuntime error: Index out of range
CNo error, test runs successfully
DCompilation error: Missing return statement
Attempts:
2 left
💡 Hint

Look at how the array is declared and what method is called on it.

📝 Syntax
advanced
1:30remaining
Correct syntax for measure block

Which option shows the correct syntax to measure the performance of sorting an array in XCTest?

A
measure {
    let sorted = array.sort
}
B
measure() {
    let sorted = array.sorted()
}
C
measure {
    let sorted = array.sort()
}
D
measure {
    let sorted = array.sorted()
}
Attempts:
2 left
💡 Hint

Remember the difference between sorted() and sort() methods.

🚀 Application
expert
2:30remaining
Analyzing performance test results

You run a performance test with this code:

func testPerformance() {
    measure {
        for _ in 1...1000 {
            _ = (1...1000).map { $0 * 2 }
        }
    }
}

The average time reported is unexpectedly high. Which change will most likely improve the accuracy of the performance measurement?

AReplace <code>map</code> with a <code>for</code> loop inside <code>measure</code>
BMove the <code>for</code> loop outside the <code>measure</code> block
CReduce the number of iterations inside the <code>measure</code> block
DRemove the <code>measure</code> block and run the code once
Attempts:
2 left
💡 Hint

Think about what the measure block repeats and what you want to measure.