【发布时间】:2022-07-06 23:18:52
【问题描述】:
我正在编写一个包含 I/O 操作小基准的应用程序。 对于写操作,我使用了一个运行良好的“FileHandle”。我正在测试我的旧 U 盘,我的计算结果大约是 20MB/s,这似乎是正确的。
但是,在读取时,值会跃升至 8 GB/s。虽然我很想拥有这么快的 U 盘……我认为这与某种缓存有关。
这是我正在使用的代码(删除了一些位):
guard let handle = FileHandle(forUpdatingAtPath: url.path) else { return }
let data = Data(repeating: 0, count: 2 * 1024 * 1024)
var startTime = Date.timestamp
// Write Test
while Date.timestamp - startTime < 5.0
{
handle.write(data)
try? handle.synchronize()
// ...
}
// Go back to beginning of file.
try? handle.seek(toOffset: 0)
// Remove everything at the end of the file
try? handle.truncate(atOffset: blockSize)
startTime = Date.timestamp
// Read Test
while Date.timestamp - startTime < 5.0
{
autoreleasepool
{
if let handle = try? FileHandle(forReadingFrom: fileUrl), let data = try? handle.readToEnd()
{
let count = UInt64(data.count)
self.readData += count
self.totalReadData += count
handle.close()
}
// I also tried FileManager.default.contents(atPath: ) - same result
}
}
我也尝试了这段代码(它来自 Martin R. here on SO 或 Quinn on the Apple forums):
let fd = open(fileUrl.path, O_RDONLY)
_ = fcntl(fd, F_NOCACHE, 1)
var buffer = Data(count: 1024 * 1024)
buffer.withUnsafeMutableBytes { ptr in
let amount = read(fd, ptr.baseAddress, ptr.count)
self.readData += UInt64(amount)
self.totalReadData += UInt64(amount)
}
close(fd)
代码本身可以工作...但仍有缓存。
TL;DR 如何在使用 Swift 读写文件时禁用缓存?
问候
【问题讨论】:
标签: swift nsfilemanager filehandle nsfilehandle