3

I need the PAGESIZE value each time my function is called, it's looks like caching system call sysconf(_SC_PAGESIZE) in a function static variable is much faster than calling it every time.

man page says:

The values obtained from these functions are system configuration constants. They do not change during the lifetime of a process.

Then, why successive calls to sysconf are so slow if value does not change ?

Here is the code I used to test:

#include <unistd.h>
long a()
{
  return sysconf(_SC_PAGESIZE);
}
long b()
{
  static long n;
  if (!n)
    n = sysconf(_SC_PAGESIZE);
  return n;
}
int main()
{
  for (int i = 800000000; i > 0; --i)
    a();
  return 0;
}

Result are: 4,8s for a() vs 1,7s for b(). It is even worse with -O2.

kiwixz
  • 1,380
  • 15
  • 23
  • 1
    sys calls are not free - actually any call to nontrivial function will have significant impact in this case (800 mln calls) - do value caching on your side – Anty Jan 29 '17 at 00:57
  • @kiwixz It's probably implemented in some trivial fashion without caching. Given that, `sysconf` requests for pagesize are actually pretty cheap, compared to requests for other properties http://stackoverflow.com/questions/23599074/system-calls-overhead/41783404#41783404. Pagesize is made available through the auxiliary vector on linux which makes obtaining it actually very cheap compared to other system calls. – Petr Skocik Jan 29 '17 at 01:06
  • 1
    Try `getpagesize()`? – DYZ Jan 29 '17 at 01:10
  • @DYZ man page says it's legacy and not really portable, so I guess I should not :( – kiwixz Jan 29 '17 at 01:37
  • 1
    For `b()` it *should* take 0s, since the compiler should hoist the conditional out as a loop termination condition and break after the first iteration. – R.. GitHub STOP HELPING ICE Jan 29 '17 at 02:04

0 Answers0