How to measure execution speed in Swift


Greetings, traveler!

There are often situations when it would be helpful to know how fast our code is executed. This can be done with the CFAbsoluteTimeGetCurrent(). It reads the current system time measured in seconds since January 1st, 2001, and returns a Double value.

We just need to determine the start and end times of code execution and then calculate the difference. You can do it this way.

let startTime = CFAbsoluteTimeGetCurrent()

// do something...

let endTime = CFAbsoluteTimeGetCurrent() - startTime

print(String(format: "%.5f sec.", endTime))

To avoid writing the same code every time, you can make a small but convenient tool that will allow you to measure the speed of execution of functions. Let’s create a Benchmark structure. It will have two private constants: the name of the function and the start time. We will define their value in the initializer. For the name of the function whose speed we will measure, we will set the default value as a literal expression of it.

struct Benchmark {

    private let name: String
    private let startTime: CFAbsoluteTime
    
    init(_ name: String = #function) {
        self.name = name
        self.startTime = CFAbsoluteTimeGetCurrent()
    }
    
    @discardableResult
    func stop() -> Double {
        let endTime = CFAbsoluteTimeGetCurrent() - startTime
        print(String(format: "\(name): %.5f sec.", endTime))
        
        return endTime
    }
    
}

Now, let’s create a service inside which there will be a network request, the speed we want to measure.

class Service {
    
    func makeURLRequest() {      
        let url = URL(string: "https://livsycode.com")!
        
        URLSession.shared.dataTask(with: url) { _, _, _ in
							
        }.resume()
    }
    
}

Before creating a request, we initialize our structure. After receiving the data, we can call the stop() function.

class Service {
    
    func makeURLRequest() {
        let benchmark = Benchmark()
        
        let url = URL(string: "https://livsycode.com")!
        
        URLSession.shared.dataTask(with: url) { _, _, _ in
            benchmark.stop() // makeURLRequest(): 1.06825 sec
        }.resume()
    }
    
}

Done!

Conclusion

We have studied a convenient approach for measuring the speed of code execution. This approach can help us understand whether processes need optimization or check the optimization’s result. I hope it was helpful for you to learn about this. See you soon!