gpt4 book ai didi

swift - Swift 中最快的逐字符读取器是什么

转载 作者:行者123 更新时间:2023-11-30 12:55:30 25 4
gpt4 key购买 nike

我必须用 swift 中的字符读取器编写一个真正的快速字符。这是我到目前为止的解决方案。

对于 1.4mb 的文件,我在 0m0.932s 内得到它。对于 150mb 的文件,需要 1m42.931s

您知道更快的解决方案吗?

import Foundation
class CharReader {

let encoding : String.Encoding
let chunkSize : Int
var fileHandle : FileHandle!
let buffer : NSMutableData!
var atEof : Bool = false
var characterPointer: UnsafeMutablePointer<Character>
var startPointer: UnsafeMutablePointer<Character>

var stored_cnt: Int = 0;
var stored_idx: Int = 0;

init?(path: String, encoding: String.Encoding = String.Encoding.utf8, chunkSize : Int = 1024) {
self.chunkSize = chunkSize
self.encoding = encoding
characterPointer = UnsafeMutablePointer<Character>.allocate(capacity: chunkSize)
startPointer = characterPointer
if let fileHandle = FileHandle(forReadingAtPath: path),
let buffer = NSMutableData(capacity: chunkSize){
self.fileHandle = fileHandle
self.buffer = buffer
} else {
self.fileHandle = nil
self.buffer = nil
return nil
}
}

deinit {
self.close()
}

func nextChar() -> Character? {

if atEof {
return nil
}

if stored_cnt > (stored_idx + 1) {
stored_idx += 1
let char = characterPointer.pointee
characterPointer = characterPointer.successor()
return char
}

let tmpData = fileHandle.readData(ofLength: (chunkSize))
if tmpData.count == 0 {
atEof = true
return nil
}

if let s = NSString(data: tmpData, encoding: encoding.rawValue) as String! {
stored_idx = 0
let characters = s.characters
stored_cnt = characters.count

characterPointer = startPointer
characterPointer.initialize(from: characters)

let char = characterPointer.pointee
characterPointer = characterPointer.successor()
return char
}
return nil;
}


/// Close the underlying file. No reading must be done after calling this method.
func close() -> Void {
fileHandle?.closeFile()
fileHandle = nil
}

}

请告诉我。

我用这个 main.swfit 测试这个类:

import Foundation

if CommandLine.arguments.count < 2 {
print("Too less arguments.")
exit(0)
}
let file = CommandLine.arguments[1]

if let aCharReader = CharReader(path: file) {
defer {
aCharReader.close()
}
while let char = aCharReader.nextChar() {
continue
}
}

该项目位于 GitHub 上:https://github.com/petershaw/charsinfile

非常感谢,附:

最佳答案

我更新了存储库,其中包含两个版本:https://github.com/petershaw/charsinfile

在 Martin 的帮助下,我修复了 Rob 代码中的错误。

我测试了一堆不同的文件,两个版本都工作正常。 Rob Napier 的代码效率更高!非常感谢,罗布。

感谢你们所有人帮助我找到最快的解决方案。很高兴这里有一个如此精彩和礼貌的社区,提供与 swift 和 cocoa 相关的东西。

祝你度过愉快的一周!

ps

关于swift - Swift 中最快的逐字符读取器是什么,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40450190/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com