我想根据系统驱动器是否是SSD来改变我的C ++应用程序的性能和行为。 例如:
我见过http://msdn.microsoft.com/en-gb/library/windows/desktop/aa364939(v=vs.85).aspx,这是一种确定某个驱动器是否是HDD,CD ROM,DVD ROM,可移动媒体等的方法,但它仍然无法检测主系统是否驱动是一个SSD。 我也见过Is there any way of detecting if a drive is a SSD?,但该解决方案仅适用于Linux。
我认为我可以以某种方式生成大的精细(500MB),然后计算写入文件所需的时间,但是其他系统变量很容易影响结果。
在Windows中,使用C ++,有没有办法让主系统驱动器是否是SSD?
答案 0 :(得分:16)
完成了一些研究并使用了本页答案中的信息,这是我在Windows 7及更高版本中使用C WinAPI实现的:
//Open drive as such: "\\?\PhysicalDriveX" where X is the drive number
//INFO: To get drive number from a logical drive letter, check this method:
// (But keep in mind that a single logical drive, or a volume,
// can span across several physical drives, as a "spanned volume.")
// http://stackoverflow.com/a/11683906/843732
#include <WinIoCtl.h>
#include <Ntddscsi.h>
DWORD bytesReturned;
//As an example, let's test 1st physical drive
HANDLE hDevice = ::CreateFile(L"\\\\?\\PhysicalDrive0",
GENERIC_READ | GENERIC_WRITE, //We need write access to send ATA command to read RPMs
FILE_SHARE_READ | FILE_SHARE_WRITE, NULL,
OPEN_EXISTING, 0, NULL);
if(hDevice != INVALID_HANDLE_VALUE)
{
//Check TRIM -- should be Y for SSD
_tprintf(L"TRIM=");
STORAGE_PROPERTY_QUERY spqTrim;
spqTrim.PropertyId = (STORAGE_PROPERTY_ID)StorageDeviceTrimProperty;
spqTrim.QueryType = PropertyStandardQuery;
bytesReturned = 0;
DEVICE_TRIM_DESCRIPTOR dtd = {0};
if(::DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
&spqTrim, sizeof(spqTrim), &dtd, sizeof(dtd), &bytesReturned, NULL) &&
bytesReturned == sizeof(dtd))
{
//Got it
_tprintf(L"%s", dtd.TrimEnabled ? L"Y" : L"N");
}
else
{
//Failed
int err = ::GetLastError();
_tprintf(L"?");
}
//Check the seek-penalty value -- should be N for SSD
_tprintf(L", seekPenalty=");
STORAGE_PROPERTY_QUERY spqSeekP;
spqSeekP.PropertyId = (STORAGE_PROPERTY_ID)StorageDeviceSeekPenaltyProperty;
spqSeekP.QueryType = PropertyStandardQuery;
bytesReturned = 0;
DEVICE_SEEK_PENALTY_DESCRIPTOR dspd = {0};
if(::DeviceIoControl(hDevice, IOCTL_STORAGE_QUERY_PROPERTY,
&spqSeekP, sizeof(spqSeekP), &dspd, sizeof(dspd), &bytesReturned, NULL) &&
bytesReturned == sizeof(dspd))
{
//Got it
_tprintf(L"%s", dspd.IncursSeekPenalty ? L"Y" : L"N");
}
else
{
//Failed
int err = ::GetLastError();
_tprintf(L"?");
}
//Get drive's RPMs reading -- should be 1 for SSD
//CODE SOURCE: https://emoacht.wordpress.com/2012/11/06/csharp-ssd/
_tprintf(L", RPM=");
ATAIdentifyDeviceQuery id_query;
memset(&id_query, 0, sizeof(id_query));
id_query.header.Length = sizeof(id_query.header);
id_query.header.AtaFlags = ATA_FLAGS_DATA_IN;
id_query.header.DataTransferLength = sizeof(id_query.data);
id_query.header.TimeOutValue = 5; //Timeout in seconds
id_query.header.DataBufferOffset = offsetof(ATAIdentifyDeviceQuery, data[0]);
id_query.header.CurrentTaskFile[6] = 0xec; // ATA IDENTIFY DEVICE
bytesReturned = 0;
if(::DeviceIoControl(hDevice, IOCTL_ATA_PASS_THROUGH,
&id_query, sizeof(id_query), &id_query, sizeof(id_query), &bytesReturned, NULL) &&
bytesReturned == sizeof(id_query))
{
//Got it
//Index of nominal media rotation rate
//SOURCE: http://www.t13.org/documents/UploadedDocuments/docs2009/d2015r1a-ATAATAPI_Command_Set_-_2_ACS-2.pdf
// 7.18.7.81 Word 217
//QUOTE: Word 217 indicates the nominal media rotation rate of the device and is defined in table:
// Value Description
// --------------------------------
// 0000h Rate not reported
// 0001h Non-rotating media (e.g., solid state device)
// 0002h-0400h Reserved
// 0401h-FFFEh Nominal media rotation rate in rotations per minute (rpm)
// (e.g., 7 200 rpm = 1C20h)
// FFFFh Reserved
#define kNominalMediaRotRateWordIndex 217
_tprintf(L"%d", (UINT)id_query.data[kNominalMediaRotRateWordIndex]);
}
else
{
//Failed
int err = ::GetLastError();
_tprintf(L"?");
}
_tprintf(L"\n");
::CloseHandle(hDevice);
}
如果您没有包含DDK驱动程序,请在此处提供一些定义:
#ifndef StorageDeviceTrimProperty
#define StorageDeviceTrimProperty 8
#endif
#ifndef DEVICE_TRIM_DESCRIPTOR
typedef struct _DEVICE_TRIM_DESCRIPTOR {
DWORD Version;
DWORD Size;
BOOLEAN TrimEnabled;
} DEVICE_TRIM_DESCRIPTOR, *PDEVICE_TRIM_DESCRIPTOR;
#endif
#ifndef StorageDeviceSeekPenaltyProperty
#define StorageDeviceSeekPenaltyProperty 7
#endif
#ifndef DEVICE_SEEK_PENALTY_DESCRIPTOR
typedef struct _DEVICE_SEEK_PENALTY_DESCRIPTOR {
DWORD Version;
DWORD Size;
BOOLEAN IncursSeekPenalty;
} DEVICE_SEEK_PENALTY_DESCRIPTOR, *PDEVICE_SEEK_PENALTY_DESCRIPTOR;
#endif
struct ATAIdentifyDeviceQuery
{
ATA_PASS_THROUGH_EX header;
WORD data[256];
};
最后,我的测试结束了。
我有几个通过SATA电缆连接的三星SSD,以及一个使用PCIe插槽直接连接到逻辑板的PCIe SSD驱动器。我还有一个大型内置Western Digital HDD(旋转驱动器),它也通过SATA线连接,还有几个外置旋转硬盘。
这是我得到的东西:
Samsung SSD 256GB: TRIM=Y, seekPenalty=N, RPM=1
Samsung SSD 500GB: TRIM=Y, seekPenalty=N, RPM=1
PCIs SSD: TRIM=Y, seekPenalty=?, RPM=0
Internal WD HDD: TRIM=N, seekPenalty=?, RPM=0
External WD HDD: TRIM=?, seekPenalty=?, RPM=?
External Cavalry HDD: TRIM=?, seekPenalty=Y, RPM=?
如您所见,在我的情况下,所有6个驱动器唯一正确的参数是TRIM。我并不是说它也会出现在你的情况中。这只是我对我拥有的驱动器的发现。
答案 1 :(得分:15)
我相信你使用的是错误的工具。您不应该根据驱动器作为SSD进行假设,而应该使用慢速和快速驱动器使代码正常工作,例如首先加载基本对象,然后再加载其余对象。在三年内,[...]的发明可能使常规硬盘驱动器比SSD更快,这会破坏您的代码。 纯粹基于速度也适用于RAM光盘,NFS,USB3.0棒和其他你没有或不可能的东西。
编辑:硬盘实际上与慢速SSD不同。虽然他们快速阅读和写入硬盘需要大量的时间来寻找。因此,使用两种不同的访问策略是有意义的:通过SSD的随机访问选择重要数据并顺序读取HDD。您可能只会实施顺序策略,因为它仍然适用于SSD。虽然检查硬盘而不是SSD更有意义,因为你需要对HDD进行特殊处理,而SSD,RAMdisc,NFS等不应该受到寻道时间的影响,因此可以对其进行处理。
答案 2 :(得分:13)
您可以使用Microsoft WMI类MSFT_PhysicalDisk。 4的mediatype是SSD,SpindleSpeed将为0.有关详细信息,请参阅链接。
https://msdn.microsoft.com/en-us/library/windows/desktop/hh830532(v=vs.85)
答案 3 :(得分:6)
是的,确定驱动器是否为SSD的可能性很高。 SSD通常支持TRIM命令,因此我会检查驱动器是否支持TRIM命令。
在Windows中,您可以使用IOCTL_STORAGE_QUERY_PROPERTY获取DEVICE_TRIM_DESCRIPTOR结构,该结构将告诉您是否已启用TRIM。
如果您真的知道自己在做什么,可以获取原始IDENTIFY DEVICE包,并自行解释数据。对于SATA驱动器,它将是字169位0。
答案 4 :(得分:5)
不要打扰驱动器类型。通过阅读一些加载的游戏数据进行测量,并决定使用哪种策略。 (别忘了制作配置选项:)
我的直觉告诉我这种方法是错误的。如果某人有一个慢盘,那么预加载应该更重要,因为在飞行中加载会导致口吃。另一方面,如果驱动器足够快,我不需要浪费内存,因为我可以快速加载数据。答案 5 :(得分:-1)
我发现的最好方法是使用WMI在ROOT \\ microsoft \ windows \ storage命名空间中使用MSFT_PhysicalDisk
这给你两个属性
媒体类型为您提供价值
主轴速度为0很不言而喻
Main.cpp
#include <iostream>
#include <windows.h>;
#include <Wbemidl.h>
#include <comdef.h>
#include "StorageDevice.h"
#include <vector>
#pragma comment(lib, "wbemuuid.lib")
using namespace::std;
void IntializeCOM()
{
HRESULT hres;
hres = CoInitializeEx(0, COINIT_MULTITHREADED);
if (FAILED(hres))
{
cout << "Failed to initialize COM library. Error code = 0x" << hex << hres << endl;
// Program has failed.
}
// Step 2: --------------------------------------------------
// Set general COM security levels --------------------------
hres = CoInitializeSecurity(
NULL,
-1, // COM authentication
NULL, // Authentication services
NULL, // Reserved
RPC_C_AUTHN_LEVEL_DEFAULT, // Default authentication
RPC_C_IMP_LEVEL_IMPERSONATE, // Default Impersonation
NULL, // Authentication info
EOAC_NONE, // Additional capabilities
NULL // Reserved
);
if (FAILED(hres))
{
cout << "Failed to initialize security. Error code = 0x" << hex << hres << endl;
CoUninitialize(); // Program has failed.
}
}
void SetupWBEM(IWbemLocator*& pLoc, IWbemServices*& pSvc)
{
// Step 3: ---------------------------------------------------
// Obtain the initial locator to WMI -------------------------
HRESULT hres;
//IWbemLocator *pLoc = NULL;
hres = CoCreateInstance(CLSID_WbemLocator, 0, CLSCTX_INPROC_SERVER, IID_IWbemLocator, (LPVOID *)&pLoc);
if (FAILED(hres))
{
cout << "Failed to create IWbemLocator object." << " Err code = 0x" << hex << hres << endl;
CoUninitialize();
}
// Step 4: -----------------------------------------------------
// Connect to WMI through the IWbemLocator::ConnectServer method
//IWbemServices *pSvc = NULL;
// Connect to the ROOT\\\microsoft\\windows\\storage namespace with
// the current user and obtain pointer pSvc
// to make IWbemServices calls.
hres = pLoc->ConnectServer(
_bstr_t(L"ROOT\\\microsoft\\windows\\storage"), // Object path of WMI namespace
NULL, // User name. NULL = current user
NULL, // User password. NULL = current
0, // Locale. NULL indicates current
NULL, // Security flags.
0, // Authority (for example, Kerberos)
0, // Context object
&pSvc // pointer to IWbemServices proxy
);
if (FAILED(hres))
{
cout << "Could not connect. Error code = 0x" << hex << hres << endl;
pLoc->Release();
CoUninitialize();
}
// Step 5: --------------------------------------------------
// Set security levels on the proxy -------------------------
hres = CoSetProxyBlanket(
pSvc, // Indicates the proxy to set
RPC_C_AUTHN_WINNT, // RPC_C_AUTHN_xxx
RPC_C_AUTHZ_NONE, // RPC_C_AUTHZ_xxx
NULL, // Server principal name
RPC_C_AUTHN_LEVEL_CALL, // RPC_C_AUTHN_LEVEL_xxx
RPC_C_IMP_LEVEL_IMPERSONATE, // RPC_C_IMP_LEVEL_xxx
NULL, // client identity
EOAC_NONE // proxy capabilities
);
if (FAILED(hres))
{
cout << "Could not set proxy blanket. Error code = 0x" << hex << hres << endl;
pSvc->Release();
pLoc->Release();
CoUninitialize();
}
}
int main()
{
IWbemLocator *wbemLocator = NULL;
IWbemServices *wbemServices = NULL;
IntializeCOM();
SetupWBEM(wbemLocator, wbemServices);
IEnumWbemClassObject* storageEnumerator = NULL;
HRESULT hres = wbemServices->ExecQuery(
bstr_t("WQL"),
bstr_t("SELECT * FROM MSFT_PhysicalDisk"),
WBEM_FLAG_FORWARD_ONLY | WBEM_FLAG_RETURN_IMMEDIATELY,
NULL,
&storageEnumerator);
if (FAILED(hres))
{
cout << "Query for MSFT_PhysicalDisk. Error code = 0x" << hex << hres << endl;
wbemServices->Release();
wbemLocator->Release();
CoUninitialize();
}
IWbemClassObject *storageWbemObject = NULL;
ULONG uReturn = 0;
vector<StorageDevice> storageDevices;
while (storageEnumerator)
{
HRESULT hr = storageEnumerator->Next(WBEM_INFINITE, 1, &storageWbemObject, &uReturn);
if (0 == uReturn)
{
break;
}
StorageDevice storageDevice;
VARIANT deviceId;
VARIANT busType;
VARIANT healthStatus;
VARIANT spindleSpeed;
VARIANT mediaType;
storageWbemObject->Get(L"DeviceId", 0, &deviceId, 0, 0);
storageWbemObject->Get(L"BusType", 0, &busType, 0, 0);
storageWbemObject->Get(L"HealthStatus", 0, &healthStatus, 0, 0);
storageWbemObject->Get(L"SpindleSpeed", 0, &spindleSpeed, 0, 0);
storageWbemObject->Get(L"MediaType", 0, &mediaType, 0, 0);
storageDevice.DeviceId = deviceId.bstrVal == NULL ? "" : _bstr_t(deviceId.bstrVal);
storageDevice.BusType = busType.uintVal;
storageDevice.HealthStatus = healthStatus.uintVal;
storageDevice.SpindleSpeed = spindleSpeed.uintVal;
storageDevice.MediaType = mediaType.uintVal;
storageDevices.push_back(storageDevice);
storageWbemObject->Release();
}
}
程序将磁盘属性存储在此处的强类型对象“ storageDevice”中,并将其推送到向量上,以便我们稍后使用
StorageDevice.h
#pragma once
#include <iostream>
using namespace::std;
class StorageDevice
{
public:
StorageDevice();
~StorageDevice();
string DeviceId;
int BusType;
int HealthStatus;
int SpindleSpeed;
int MediaType;
};
StorageDevice.cpp
#include "StorageDevice.h"
StorageDevice::StorageDevice()
{
}
StorageDevice::~StorageDevice()
{
}
视频教程和源代码c ++ download here