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

14,579

Solution 1

On Win32, GetLogicalProcessorInformation will give you back a SYSTEM_LOGICAL_PROCESSOR_INFORMATION which contains a CACHE_DESCRIPTOR, which has the information you need.

Solution 2

On Linux try the proccpuinfo library, an architecture independent C API for reading /proc/cpuinfo

Solution 3

For x86, the CPUID instruction. A quick google search reveals some libraries for win32 and c++. I have used CPUID via inline assembler as well.

Some more info:

Solution 4

Looks like at least SCO unix (http://uw714doc.sco.com/en/man/html.3C/sysconf.3C.html) has _SC_CACHE_LINE for sysconf. Perhaps other platforms have something similar?

Solution 5

On 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();
}

On Linux

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

Share:
14,579
Mathieu Pagé
Author by

Mathieu Pagé

My languages of interest are C++, C#, ASP.NET, python.

Updated on June 18, 2022

Comments

  • Mathieu Pagé
    Mathieu Pagé almost 2 years

    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 and another for Windows (Solutions for other systems could be usefull to others, so post them if you know them).

    For Linux I could read the content of /proc/cpuinfo and parse the line begining with cache_alignment. Maybe there is a better way involving a call to an API.

    For Windows I simply have no idea.