iOS Dev Nugget 264 Track how long a function takes to run and report progress


Need to run a code review on your codebase? Hire me

Often when comparing implementations of the same function, I need to do some simple profiling to compare the total time taken. The simplest approach is to create a Date instance before and after the operation and calculate the difference. These are usually long operations and I want to track progress. This becomes a bit more troublesome when the operation is asynchronous. So I wrote a simple class to help:

import Foundation

class ProgressReporter {
    let startTime = Date()
    var name: String
    var total: Int
    var step: Int

    init(name: String, total: Int = -1, step: Int = 100000) { = name = total
        self.step = step

    func update(current: Int, completion: (()->())? = nil) {
        if current % step == 0 {
            print("Progress \(current)/\(total)")
        if current == total {

    func completed() {
        print("Time taken to \(name): \(Date().timeIntervalSince(startTime)) secs")

extension String {
    var firstUppercased: String {
        guard let first = first else { return "" }
        return String(first).uppercased() + dropFirst()

You can use it like this:

func getFileNames(someInput: [String]) {
    let progress = ProgressReporter(name: "get filenames", total: someInput.count)
    var results = [String]()
    for e in results {
        someAsyncOperation(e) {
            progress.update(current: results.count) {
                //do something with results

It'll print something like this:

Get filenames
Progress 100000/2000000
Progress 200000/2000000
Progress 300000/2000000
Progress 2000000/2000000
Time taken to get filenames: 100 secs

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No



Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues