我正在為 macOS 撰寫一個疊加影像的 Swift 應用程式。它作業得很好,但是當我這樣做很多時間時,記憶就會消失。
我嘗試創建一個小專案來讀取一個影像,并寫入 1000 次。影像為 15K。它占用程式 2.7 Gb 記憶體。包含 1000 張影像的實際輸出檔案夾為 14Mb。
我使用 DispatchQueue.global 讓 UI 自由顯示操作編號。
如果你有任何想法;)
謝謝,尼古拉斯
這里的代碼:
import SwiftUI
struct ContentView: View {
@State private var presentImageImporter = false
@State private var runningComputation = 1
@State private var inputImage: NSImage?
var body: some View {
VStack {
Button("Image") {
presentImageImporter = true
}.fileImporter(isPresented: $presentImageImporter, allowedContentTypes: [.png, .jpeg]) { result in
switch result {
case .success(let url):
if url.startAccessingSecurityScopedResource() {
inputImage = NSImage(byReferencing: url)
url.stopAccessingSecurityScopedResource()
}
case .failure(let error):
print(error)
}
}
Button("Compute 1000 read image") {
runComputations()
}
Divider()
Text("\(runningComputation)")
Divider()
}.frame(minWidth: 200, minHeight: 200)
}
func runComputations() {
let downloadDir = try! FileManager.default.url(
for: FileManager.SearchPathDirectory.downloadsDirectory,
in: FileManager.SearchPathDomainMask.userDomainMask,
appropriateFor: nil,
create: true)
let subFolder = downloadDir.appendingPathComponent("toto")
try! FileManager.default.createDirectory(at: subFolder, withIntermediateDirectories: true)
DispatchQueue.global(qos: .userInitiated).async {
for i in 0...1000 {
writePNG(inputImage!, url: subFolder.appendingPathComponent("image\(i).png"))
runningComputation = 1
}
}
}
}
func writePNG(_ image: NSImage, url: URL) {
let newRep = NSBitmapImageRep(data: image.tiffRepresentation!)
newRep!.size = image.size
let pngData = newRep!.representation(using: .png, properties: [:])
do {
try pngData!.write(to: url)
} catch {
print(error)
}
}
和跟蹤影像

uj5u.com熱心網友回復:
問題在這里:
for i in 0...1000 {
writePNG(inputImage!, url: subFolder.appendingPathComponent("image\(i).png"))
runningComputation = 1
}
這會在不耗盡自動釋放池的情況下創建大量臨時自動釋放物件。您會注意到,在運行結束時,記憶體使用量突然下降到 8MiB。那是默認自動釋放池耗盡的時候。
您需要將每個迭代包裝在自己的autoreleasepool塊中,以便更快地丟棄臨時物件。
for i in 0...1000 {
autoreleasepool {
writePNG(inputImage!, url: subFolder.appendingPathComponent("image\(i).png"))
runningComputation = 1
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/491641.html
上一篇:加快R中向量的setdiff()、intersect()、union()操作
下一篇:使用函式庫,成員函式呼叫性能變慢
