我撰寫了一個從兩個串列中掃描檔案(圖片)并檢查檔案是否在兩個串列中的函式。
下面的代碼按預期作業,但對于大型集合需要一些時間。因此,我嘗試與協程并行執行此操作。但是在 100 個樣本檔案的集合中,程式總是比沒有協程時慢。
代碼:
private fun doJob() {
val filesToCompare = File("C:\\Users\\Tobias\\Desktop\\Test").walk().filter { it.isFile }.toList()
val allFiles = File("\\\\myserver\\Photos\\photo").walk().filter { it.isFile }.toList()
println("Files to scan: ${filesToCompare.size}")
filesToCompare.forEach { file ->
var multipleDuplicate = 0
var s = "This file is a duplicate"
s = "\n${file.absolutePath}"
allFiles.forEach { possibleDuplicate ->
if (file != possibleDuplicate) { //only needed when both lists are the same
// Files that have the same name or contains the name, so not every file gets byte comparison
if (possibleDuplicate.nameWithoutExtension.contains(file.nameWithoutExtension)) {
try {
if (Files.mismatch(file.toPath(), possibleDuplicate.toPath()) == -1L) {
s = "\n${possibleDuplicate.absolutePath}"
i
multipleDuplicate
println(s)
}
} catch (e: Exception) {
println(e.message)
}
}
}
}
if (multipleDuplicate > 1) {
println("This file has $multipleDuplicate duplicate(s)")
}
}
println("Files scanned: ${filesToCompare.size}")
println("Total number of duplicates found: $i")
}
我是如何嘗試添加協程的?
我將代碼包裝在第一個 forEach 中launch{...}的想法是,對于每個檔案,一個協程啟動,第二個回圈同時完成。我希望程式運行得更快,但實際上它幾乎相同或更慢。
如何實作此代碼以更快地并行運行?
uj5u.com熱心網友回復:
在協程中運行每個內部回圈似乎是一種不錯的方法。問題可能出在您使用的調度程式上。如果您使用的runBlocking和launch沒有背景關系的說法,你正在使用一個單獨的執行緒來運行所有的協同程式。
由于這里主要是阻塞 IO,您可以改為使用Dispatchers.IO來啟動您的協程,因此您的協程在多個執行緒上分派。并行度應該自動限制為 64,但如果您的記憶體無法處理,您也可以使用Dispatchers.IO.limitedParallelism(n)來減少執行緒數。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/409896.html
標籤:
上一篇:Ktor-以編程方式創建多個子域
