get_page_size
Chris Packham
Chris.Packham at alliedtelesis.co.nz
Sun Jun 14 21:30:06 UTC 2020
On 15/06/20 7:11 am, Bran S wrote:
> Hi,
>
> While reading code I came across this in `tests/get_page_size.c`
>
> size_t
> get_page_size(void)
> {
> static size_t page_size;
>
> if (!page_size)
> page_size = sysconf(_SC_PAGESIZE);
>
> return page_size;
> }
>
> Why are we checking for page_size to be zero. Static variables are
> always initialized to zero by default right?
> Even if they aren't why check for zero, we can just assign the size to
> it without doing so, right?
> What am I missing here, as I am sure this cannot be a mistake?
Because page_size is a function scope static it is initialized to 0 at
compile time but it's value will be updated to the page size the first
time get_page_size() is called. Subsequent calls to get_page_size() will
skip the sysconf() and return the non-zero value. This is a reasonably
common optimization in C code.
> Also why not write the above function as:
>
> size_t
> get_page_size(void)
> {
> return sysconf(_SC_PAGESIZE);
> }
> Is it because this would be inlined and we don't want that? If so,
> then the next question would be why won't we want it to be inlined?
> Please clarify whatever it is that I am missing here.
You could indeed write it like this but then you'd have the overhead of
calling sysconf() on every invocation to fetch something that never
changes. As sysconf() ultimately ends up as a system call to the kernel
that's actually a reasonably significant overhead even if you could
eliminate all the stack frame manipulation with in-lining and link time
optimisation.
More information about the Strace-devel
mailing list