NEW! Master Swift design patterns with my latest book! >>

How to write performance tests using measure()

Paul Hudson       @twostraws

Performance tests let you check how fast your code runs, but more importantly it lets you check how fast your code runs over time – you can spot performance changes as your code evolves.

Writing a performance test takes just two steps:

  1. Create a new method starting with the name “test” in your Xcode tests.
  2. Using the measure() method inside that test, running any work you want.

To try it out, look in the “Tests” group in your Xcode project, then open your tests file. In my test I’m going to try generating images using a fictional ImageGenerator struct that has a generateImages() method. I’m specifically going to be testing the generateImages() method, which means I’ll create a test instance of ImageGenerator outside the measure() method, like this:

func testPerformanceExample() {
    let generator = ImageGenerator()

    measure {
        generator.generateImages()
    }
}

When that test runs, Xcode will run the contents of measure() 10 times to get a spread of results.

Available from iOS

Did this solution work for you? Please pass it on!

Other people are reading…

About the Swift Knowledge Base

This is part of the Swift Knowledge Base, a free, searchable collection of solutions for common iOS questions.

Test your Swift today

Think you know Swift? My book Swift Coding Challenges will put your Swift skills to the test – it's perfect for job interviews and more!

MASTER SWIFT NOW
Buy Practical iOS 12 Buy Pro Swift Buy Swift Design Patterns Buy Practical iOS 11 Buy Swift Coding Challenges Buy Server-Side Swift (Vapor Edition) Buy Server-Side Swift (Kitura Edition) Buy Hacking with macOS Buy Advanced iOS Volume One Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with Swift Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let me know!

Click here to visit the Hacking with Swift store >>