Last active
March 1, 2021 15:33
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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