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) {
self.name = name
self.total = total
self.step = step
print("\(name.firstUppercased)...")
}
func update(current: Int, completion: (()->())? = nil) {
if current % step == 0 {
print("Progress \(current)/\(total)")
}
if current == total {
completed()
completion?()
}
}
func completed() {
print("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
Completed
Time taken to get filenames: 100 secs
Your feedback is valuable: Do you want more nuggets like this? Yes or No
.
.