我希望我的程序读取它在 C++ 中运行的 CPU 的缓存行大小。
我知道这不能移植,所以我需要一个 Linux 解决方案和另一个 Windows 解决方案(其他系统的解决方案可能对其他人有用,所以如果你知道它们,请发布它们)。
对于 Linux,我可以读取 /proc/cpuinfo 的内容并解析以 cache_alignment 开头的行。也许有更好的方法涉及对 API 的调用。
对于 Windows,我根本不知道。
在 Win32 上,GetLogicalProcessorInformation
将返回 aSYSTEM_LOGICAL_PROCESSOR_INFORMATION
其中包含 a CACHE_DESCRIPTOR
,其中包含您需要的信息。
在 Linux 上尝试使用proccpuinfo 库,这是一个独立于架构的 C API,用于读取 /proc/cpuinfo
看起来至少 SCO unix ( http://uw714doc.sco.com/en/man/html.3C/sysconf.3C.html ) 有 _SC_CACHE_LINE 用于 sysconf。也许其他平台也有类似的东西?
在 Windows 上
#include <Windows.h>
#include <iostream>
using std::cout; using std::endl;
int main()
{
SYSTEM_INFO systemInfo;
GetSystemInfo(&systemInfo);
cout << "Page Size Is: " << systemInfo.dwPageSize;
getchar();
}
在 Linux 上
以下是那些想知道如何在接受的答案中使用该功能的人的示例代码:
#include <new>
#include <iostream>
#include <Windows.h>
void ShowCacheSize()
{
using CPUInfo = SYSTEM_LOGICAL_PROCESSOR_INFORMATION;
DWORD len = 0;
CPUInfo* buffer = nullptr;
// Determine required length of a buffer
if ((GetLogicalProcessorInformation(buffer, &len) == FALSE) && (GetLastError() == ERROR_INSUFFICIENT_BUFFER))
{
// Allocate buffer of required size
buffer = new (std::nothrow) CPUInfo[len]{ };
if (buffer == nullptr)
{
std::cout << "Buffer allocation of " << len << " bytes failed" << std::endl;
}
else if (GetLogicalProcessorInformation(buffer, &len) != FALSE)
{
for (DWORD i = 0; i < len; ++i)
{
// This will be true for multiple returned caches, we need just one
if (buffer[i].Relationship == RelationCache)
{
std::cout << "Cache line size is: " << buffer[i].Cache.LineSize << " bytes" << std::endl;
break;
}
}
}
else
{
std::cout << "ERROR: " << GetLastError() << std::endl;
}
delete[] buffer;
}
}
我认为你需要NtQuerySystemInformation
从ntdll.dll
.