用c语言代码测试电脑硬盘性能
时间: 2023-10-21 21:07:20 浏览: 138
在C语言中,可以使用Windows API函数来测试硬盘性能。
下面是一个简单的示例程序,可以测试硬盘的读写速度:
```c
#include <windows.h>
#include <stdio.h>
int main()
{
char szFilePath[MAX_PATH] = {"test_file.bin"};
char szBuffer[1024 * 1024] = {0};
DWORD dwBytesWritten = 0;
DWORD dwBytesRead = 0;
LARGE_INTEGER liFileSize = {0};
LARGE_INTEGER liStart = {0};
LARGE_INTEGER liEnd = {0};
HANDLE hFile = NULL;
// 创建测试文件
hFile = CreateFile(szFilePath, GENERIC_WRITE, 0, NULL, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("文件创建失败!\n");
return -1;
}
memset(szBuffer, 'A', sizeof(szBuffer));
if (!WriteFile(hFile, szBuffer, sizeof(szBuffer), &dwBytesWritten, NULL))
{
printf("文件写入失败!\n");
CloseHandle(hFile);
return -1;
}
CloseHandle(hFile);
// 获取文件大小
hFile = CreateFile(szFilePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("文件打开失败!\n");
return -1;
}
GetFileSizeEx(hFile, &liFileSize);
CloseHandle(hFile);
// 顺序读取文件
hFile = CreateFile(szFilePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("文件打开失败!\n");
return -1;
}
QueryPerformanceCounter(&liStart);
while (ReadFile(hFile, szBuffer, sizeof(szBuffer), &dwBytesRead, NULL) && dwBytesRead != 0)
{
// 读取文件内容
}
QueryPerformanceCounter(&liEnd);
CloseHandle(hFile);
// 输出顺序读取速度
printf("顺序读取速度:%lf MB/s\n", (double)liFileSize.QuadPart / 1024 / 1024 / ((double)(liEnd.QuadPart - liStart.QuadPart) / (double)liFileSize.QuadPart));
// 随机读取文件
hFile = CreateFile(szFilePath, GENERIC_READ, 0, NULL, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
if (hFile == INVALID_HANDLE_VALUE)
{
printf("文件打开失败!\n");
return -1;
}
QueryPerformanceCounter(&liStart);
for (int i = 0; i < 1000; i++)
{
LARGE_INTEGER liOffset = {0};
liOffset.QuadPart = ((double)rand() / RAND_MAX) * liFileSize.QuadPart;
SetFilePointerEx(hFile, liOffset, NULL, FILE_BEGIN);
ReadFile(hFile, szBuffer, sizeof(szBuffer), &dwBytesRead, NULL);
}
QueryPerformanceCounter(&liEnd);
CloseHandle(hFile);
// 输出随机读取速度
printf("随机读取速度:%lf MB/s\n", (double)1000 * sizeof(szBuffer) / 1024 / 1024 / ((double)(liEnd.QuadPart - liStart.QuadPart) / (double)liFileSize.QuadPart));
// 删除测试文件
DeleteFile(szFilePath);
return 0;
}
```
注意:该程序只能测试本地硬盘的性能,不能测试网络硬盘的性能。另外,需要管理员权限才能运行。
希望能帮到您!
阅读全文