我的笔记本电脑有一个 SSD 磁盘,其物理磁盘扇区大小为 512 字节,逻辑磁盘扇区大小为 4,096 字节。我正在开发一个必须绕过所有操作系统缓存的 ACID 数据库系统,因此我直接从分配的内部存储器 (RAM) 写入 SSD 磁盘。我还在运行测试之前扩展了文件,并且在测试期间不调整它的大小。
现在这是我的问题,根据SSD 基准,随机读写应该分别在 30 MB/s 到 90 MB/s 范围内。但这是我无数次性能测试中的(相当可怕的)遥测数据:
- 读取随机 512 字节块(物理扇区大小)时为 1.2 MB/s
- 写入随机 512 字节块(物理扇区大小)时为 512 KB/s
- 读取随机 4,096 字节块(逻辑扇区大小)时为 8.5 MB/s
- 写入随机 4,096 字节块(逻辑扇区大小)时为 4.9 MB/s
除了使用异步 I/OI 之外,还设置了FILE_SHARE_READ
和FILE_SHARE_WRITE
标志来禁用所有操作系统缓冲——因为我们的数据库是 ACID 我必须这样做,我也尝试过FlushFileBuffers()
,但这给了我更糟糕的性能。我还等待每个异步 I/O 操作按照我们的某些代码的要求完成。
这是我的代码,它有问题还是我陷入了这种糟糕的 I/O 性能?
HANDLE OpenFile(const wchar_t *fileName)
{
// Set access method
DWORD desiredAccess = GENERIC_READ | GENERIC_WRITE ;
// Set file flags
DWORD fileFlags = FILE_FLAG_WRITE_THROUGH | FILE_FLAG_NO_BUFFERING /*| FILE_FLAG_RANDOM_ACCESS*/;
//File or device is being opened or created for asynchronous I/O
fileFlags |= FILE_FLAG_OVERLAPPED ;
// Exlusive use (no share mode)
DWORD shareMode = 0;
HANDLE hOutputFile = CreateFile(
// File name
fileName,
// Requested access to the file
desiredAccess,
// Share mode. 0 equals exclusive lock by the process
shareMode,
// Pointer to a security attribute structure
NULL,
// Action to take on file
CREATE_NEW,
// File attributes and flags
fileFlags,
// Template file
NULL
);
if (hOutputFile == INVALID_HANDLE_VALUE)
{
int lastError = GetLastError();
std::cerr << "Unable to create the file '" << fileName << "'. [CreateFile] error #" << lastError << "." << std::endl;
}
return hOutputFile;
}
DWORD ReadFromFile(HANDLE hFile, void *outData, _UINT64 bytesToRead, _UINT64 location, OVERLAPPED *overlappedPtr,
asyncIoCompletionRoutine_t completionRoutine)
{
DWORD bytesRead = 0;
if (overlappedPtr)
{
// Windows demand that you split the file byte locttion into high & low 32-bit addresses
overlappedPtr->Offset = (DWORD)_UINT64LO(location);
overlappedPtr->OffsetHigh = (DWORD)_UINT64HI(location);
// Should we use a callback function or a manual event
if (!completionRoutine && !overlappedPtr->hEvent)
{
// No manual event supplied, so create one. The caller must reset and close it themselves
overlappedPtr->hEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
if (!overlappedPtr->hEvent)
{
DWORD errNumber = GetLastError();
std::wcerr << L"Could not create a new event. [CreateEvent] error #" << errNumber << L".";
}
}
}
BOOL result = completionRoutine ?
ReadFileEx(hFile, outData, (DWORD)(bytesToRead), overlappedPtr, completionRoutine) :
ReadFile(hFile, outData, (DWORD)(bytesToRead), &bytesRead, overlappedPtr);
if (result == FALSE)
{
DWORD errorCode = GetLastError();
if (errorCode != ERROR_IO_PENDING)
{
std::wcerr << L"Can't read sectors from file. [ReadFile] error #" << errorCode << L".";
}
}
return bytesRead;
}