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

后端 未结 7 1580
渐次进展
渐次进展 2020-12-13 04:49

I\'d like my program to read the cache line size of the CPU it\'s running on in C++.

I know that this can\'t be done portably, so I will need a solution for Linux an

7条回答
  •  青春惊慌失措
    2020-12-13 05:44

    Here is sample code for those who wonder how to to utilize the function in accepted answer:

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

提交回复
热议问题