27

我希望我的程序读取它在 C++ 中运行的 CPU 的缓存行大小。

我知道这不能移植,所以我需要一个 Linux 解决方案和另一个 Windows 解决方案(其他系统的解决方案可能对其他人有用,所以如果你知道它们,请发布它们)。

对于 Linux,我可以读取 /proc/cpuinfo 的内容并解析以 cache_alignment 开头的行。也许有更好的方法涉及对 API 的调用。

对于 Windows,我根本不知道。

4

7 回答 7

18

在 Win32 上,GetLogicalProcessorInformation将返回 aSYSTEM_LOGICAL_PROCESSOR_INFORMATION其中包含 a CACHE_DESCRIPTOR,其中包含您需要的信息。

于 2008-09-29T19:38:50.060 回答
5

在 Linux 上尝试使用proccpuinfo 库,这是一个独立于架构的 C API,用于读取 /proc/cpuinfo

于 2008-09-29T19:49:21.890 回答
4

对于 x86,CPUID指令。一个快速的谷歌搜索揭示了一些用于 win32 和 c++ 的库。我也通过内联汇编器使用了 CPUID。

更多信息:

于 2008-09-29T19:46:10.697 回答
3

看起来至少 SCO unix ( http://uw714doc.sco.com/en/man/html.3C/sysconf.3C.html ) 有 _SC_CACHE_LINE 用于 sysconf。也许其他平台也有类似的东西?

于 2008-09-29T19:38:19.997 回答
3

在 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 上

http://linux.die.net/man/2/getpagesize

于 2016-09-13T09:25:46.607 回答
2

以下是那些想知道如何在接受的答案中使用该功能的人的示例代码:

#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;
    }
}
于 2020-05-27T13:56:43.793 回答
0

我认为你需要NtQuerySystemInformationntdll.dll.

于 2008-09-29T19:45:14.927 回答