Last active
May 2, 2023 08:54
-
-
Save tgrapperon/a38cf03e83b4e5e31a0282ba00014f3a to your computer and use it in GitHub Desktop.
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
import Foundation | |
public func printStackDepth( | |
label: String? = nil, | |
fileID: StaticString = #fileID, | |
line: UInt = #line | |
) { | |
let thread = pthread_self() | |
let stackAddress = UInt(bitPattern: pthread_get_stackaddr_np(thread)) | |
var used: UInt = 0 | |
withUnsafeMutablePointer(to: &used) { | |
let pointerAddress = UInt(bitPattern: $0) | |
// Stack goes down on x86/64 and arm, but we rectify the result in any case this code | |
// executes on another architecture using a different convention. | |
$0.pointee = | |
stackAddress > pointerAddress | |
? stackAddress - pointerAddress | |
: pointerAddress - stackAddress | |
} | |
let stackSize = UInt(pthread_get_stacksize_np(thread)) | |
let usedFraction = Double(used) / Double(stackSize) | |
func separated(_ number: UInt) -> String { | |
var separated = [String]() | |
for (index, char) in "\(number)".reversed().enumerated() { | |
if index > 0, index.isMultiple(of: 3) { | |
separated.append(",") | |
} | |
separated.append("\(char)") | |
} | |
return separated.reversed().joined() | |
} | |
func padded(_ number: UInt) -> String { | |
let length = separated(stackSize).count | |
let separatedNumber = separated(number) | |
let padding = String(repeating: " ", count: max(0, length - separatedNumber.count)) | |
return padding + separatedNumber | |
} | |
func filename(_ fileID: StaticString) -> String { | |
"\(fileID)".components(separatedBy: "/").last!.replacingOccurrences(of: ".swift", with: "") | |
} | |
let prefix = label.map { "\($0)" } ?? "\(filename(fileID)):l\(line)" | |
let message = """ | |
\(prefix) Stack Depth: \ | |
\(padded(used))/\(separated(stackSize)) bytes \ | |
(\(String(format: "%.2f%%", usedFraction * 100))) | |
""" | |
print(message) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment