UPGRADE YOUR SKILLS: Learn advanced Swift and SwiftUI on Hacking with Swift+! >>

How to write performance tests using measure()

Swift version: 5.6

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.

TAKE YOUR SKILLS TO THE NEXT LEVEL If you like Hacking with Swift, you'll love Hacking with Swift+ – it's my premium service where you can learn advanced Swift and SwiftUI, functional programming, algorithms, and more. Plus it comes with stacks of benefits, including monthly live streams, downloadable projects, a 20% discount on all books, and free gifts!

Find out more

Sponsor Hacking with Swift and reach the world's largest Swift community!

Available from iOS

Similar solutions…

About the Swift Knowledge Base

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

BUY OUR BOOKS
Buy Pro Swift Buy Pro SwiftUI Buy Swift Design Patterns Buy Testing Swift Buy Hacking with iOS Buy Swift Coding Challenges Buy Swift on Sundays Volume One Buy Server-Side Swift Buy Advanced iOS Volume One Buy Advanced iOS Volume Two Buy Advanced iOS Volume Three Buy Hacking with watchOS Buy Hacking with tvOS Buy Hacking with macOS Buy Dive Into SpriteKit Buy Swift in Sixty Seconds Buy Objective-C for Swift Developers Buy Beyond Code

Was this page useful? Let us know!

Average rating: 4.2/5

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.