get_page_size
Bran S
archsbran at gmail.com
Mon Jun 15 20:05:15 UTC 2020
On Mon, 15 Jun 2020 at 03:00, Chris Packham
<Chris.Packham at alliedtelesis.co.nz> wrote:
>
>
> 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.
Thanks for the explanation, makes sense now.
One last query, I see that get_page_size() is being called at 25 places.
What is the reason to not make it a global variable and save all this?
A design choice?
More information about the Strace-devel
mailing list