Skip to content
systemcoding.dev
Performance

Get the L1 cache line size with sysconf(_SC_LEVEL1_DCACHE_LINESIZE)

Get the L1 data cache line size at run time with sysconf(_SC_LEVEL1_DCACHE_LINESIZE) in glibc 2.41, and handle the 0 it returns when the value is unknown.

1 min read
Summarize in AI

Padding and alignment code needs the cache line size, and hard-coding 64 is wrong on some CPUs. glibc 2.41 exposes it through sysconf(_SC_LEVEL1_DCACHE_LINESIZE), a glibc extension that is not in POSIX.

linesize.cc
#include <stdio.h>
#include <unistd.h>

int main(void) {
    long line = sysconf(_SC_LEVEL1_DCACHE_LINESIZE);
    if (line <= 0)
        line = 64;               /* unknown: fall back */
    printf("line=%ld\n", line);
    return 0;
}
Text
line=64

On most x86-64 machines the answer is 64, which is what you see here. On some architectures, glibc cannot read the value and returns 0, so a fallback is not optional. The _SC_LEVEL1_* names are listed in the sysconf(3) man page. If the program must run on musl or on macOS, this constant does not exist there, and you need sysctl hw.cachelinesize on macOS or the sysfs file /sys/devices/system/cpu/cpu0/cache/index0/coherency_line_size on Linux instead. Query it once at startup, not in a hot path.

Taggedcglibc
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.