Skip to content

Instantly share code, notes, and snippets.

@JasonCanCode
Last active March 1, 2021 15:33
Show Gist options
  • Save JasonCanCode/eea29f4545635dc8186f2142db06822d to your computer and use it in GitHub Desktop.
Save JasonCanCode/eea29f4545635dc8186f2142db06822d to your computer and use it in GitHub Desktop.
Helpful tool for printing to console when you are trying to figure out what is taking so long
class Stopwatch {
static let shared = Stopwatch()
let name: String
var shouldLogInRealTime: Bool = false
private var start: Date? {
willSet {
lap = newValue
}
}
private var lap: Date?
private var printLines: [String] = []
init(named name: String = "") {
self.name = name
}
func markStart() {
printLines = []
start = Date()
let name = self.name.isEmpty
? "SHARED"
: "\"\(self.name)\""
printOut("\n\n**************** \(name) STOPWATCH STARTED ****************\n")
}
func markLap(named: String = "") {
guard let lap = lap else {
printOut("!!!!!!! STOPWATCH ERROR !!!!!!!")
printOut("(- 0u0)- You forgot to start the Stopwatch first you big silly\n")
return
}
let now = Date()
let timePassed = now.timeIntervalSince(lap)
let timeString = String(format: "%.5f", timePassed)
printOut(" LAP: \(timeString) sec. (\(named))")
self.lap = now
}
func markStop(andPrintSummary shouldPrint: Bool = false) {
guard let start = start else {
printOut("!!!!!!!!!!!!!! STOPWATCH ERROR !!!!!!!!!!!!!!")
printOut("(- 0u0)- You forgot to start the Stopwatch first you big silly\n")
return
}
let now = Date()
let timePassed = now.timeIntervalSince(start)
let timeString = String(format: "%5f", timePassed)
printOut("\n TOTAL: \(timeString) sec.")
self.start = nil
printOut("\n**************** STOPWATCH STOPPED ****************\n\n")
if shouldPrint {
printSummary()
}
}
func printSummary() {
for line in printLines {
print(line)
}
}
private func printOut(_ line: String) {
if shouldLogInRealTime {
print(line)
}
printLines.append(line)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment