Franck Freiburger
Franck Freiburger

Reputation: 28428

detecting the memory page size

Is there a portable way to detect (programmatically) the memory page size using C or C++ code?

Upvotes: 19

Views: 20734

Answers (7)

Ted
Ted

Reputation: 923

Windows 10, Visual Studio 2017, C++. Get the page size in bytes.

int main()
{
    SYSTEM_INFO sysInfo;

    GetSystemInfo(&sysInfo);

    printf("%s %d\n\n", "PageSize[Bytes] :", sysInfo.dwPageSize);

    getchar();

    return 0;
}

Upvotes: 15

user6269400
user6269400

Reputation: 209

Across operating systems, no.

On Linux systems:

#include <unistd.h>
long sz = sysconf (_SC_PAGESIZE);

Upvotes: 12

Edmund Grimley Evans
Edmund Grimley Evans

Reputation: 121

Yes, this is platform-specific. On Linux there's sysconf(_SC_PAGESIZE), which also seems to be POSIX. A typical C library implements this using the auxiliary vector. If for some reason you don't have a C library or the auxiliary vector you could determine the page size like this:

size_t get_page_size(void)
{
    size_t n;
    char *p;
    int u;
    for (n = 1; n; n *= 2) {
        p = mmap(0, n * 2, PROT_NONE, MAP_ANONYMOUS | MAP_PRIVATE, -1, 0);
        if (p == MAP_FAILED)
            return -1;
        u = munmap(p + n, n);
        munmap(p, n * 2);
        if (!u)
            return n;
    }
    return -1;
}

That's also POSIX, I think. It relies on there being some free memory, but it only needs two consecutive pages. It might be useful in some (weird) circumstances.

Upvotes: 6

HChen
HChen

Reputation: 268

I think this function helps.
[DllImport("kernel32.dll")] public static extern void GetSystemInfo([MarshalAs(UnmanagedType.Struct)] ref SYSTEM_INFO lpSystemInfo);

Upvotes: -4

DarthCoder
DarthCoder

Reputation: 270

It is entirely platform dependent which address-ranges are mapped to which page-sizes. Further the pagesize is not system-wide. You can allocate memory from different page-size regions according to the use case. And you can even have platforms without any virtual memory managment.

So, code handling this topic must be platform specific.

Upvotes: 1

Kirill V. Lyadvinsky
Kirill V. Lyadvinsky

Reputation: 99555

Since Boost is a pretty portable library you could use mapped_region::get_page_size() function to retrieve the memory page size.

As for C++ Standard it gives no such a possibility.

Upvotes: 17

nos
nos

Reputation: 229058

C doesn't know anything about memory pages. On posix systems you can use long pagesize = sysconf(_SC_PAGE_SIZE);

Upvotes: 18

Related Questions