簡體   English   中英

如何以編程方式獲取 C++ 中的 CPU 緩存頁面大小?

[英]How to programmatically get the CPU cache page size in C++?

我希望我的程序讀取它在 C++ 中運行的 CPU 的緩存行大小。

我知道這不能移植,所以我需要一個適用於 Linux 的解決方案和另一個適用於 Windows 的解決方案(其他系統的解決方案可能對其他人有用,所以如果你知道他們,請發布它們)。

對於 Linux,我可以讀取 /proc/cpuinfo 的內容並解析以 cache_alignment 開頭的行。 也許有更好的方法涉及調用 API。

對於 Windows,我根本不知道。

在 Win32 上, GetLogicalProcessorInformation將返回一個SYSTEM_LOGICAL_PROCESSOR_INFORMATION ,其中包含一個CACHE_DESCRIPTOR ,其中包含您需要的信息。

在 Linux 上嘗試使用proccpuinfo 庫,這是一個獨立於體系結構的 C API,用於讀取 /proc/cpuinfo

對於 x86, CPUID指令。 快速的谷歌搜索顯示了一些適用於 win32 和 c++ 的 我也通過內聯匯編器使用了 CPUID。

更多信息:

看起來至少 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 上

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

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

#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;
    }
}

我認為您需要來自ntdll.dll NtQuerySystemInformation

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM