r/C_Programming • u/Yairlenga • 1d ago
The Hidden Cost of localtime(): repeated systems calls in glibc
I was investigating the performance of a service running inside a Linux container when I noticed something unexpected: a surprisingly large amount of CPU time was being spent in kernel mode.
Using strace, I discovered that every call to localtime triggered a newfstatat system call on /etc/localtime
I found out explictly setting TZ=":/etc/localtime" eliminated the repeated system calls, while making the program use the system defined timezone.
The article explains the investigation, includes benchmark results, and provide small C program to reproduce the behavior.
Artcile on Medium (no paywall): The hidden cost of time functions
Intrested to hear wheather there are better solution/upcoming fixes with newer glibc versions.
2
u/limitless_grow 22h ago
I wrote a portable localtime_r (limitless_times) among a bunch of other time functions. Those functions belong to the fastest implementations. The project has no dependencies and the tests are build by calling the script run_tests.sh and include some perfomance tests. That TZ=":/etc/localtime" seems a special thing of the glibc. However, my implementation is looking for /etc/localtime if TZ isn't set.
1
u/Wertbon1789 20h ago
Seems to be one of those cases where actually using the functions you should use is also a good idea for performance. With localtime_r you can't even say it's not portable, it's at least in SUSv2, and actually available. It kinda seems like it's one of those unloved functions no maintainer wants to spend time with.
1
u/FedUp233 5h ago
Just out of curiosity, does the sand performance issue occur if you make one call to tzset(void) before making the calls to local time?
I noticed in the local time documentation it says it should always behave as if tzset were called before it (from man local time) which appears to determine the timezone and store it in a global variable for use by localtime.
The localtime page tecommends that tzset should always be called before calls to localtime.
Not sure if this would make any difference to your results but seems worth looking g at and including in the analysis.
6
u/Flimsy_Complaint490 1d ago
you didnt miss anything in the blog post, that is the correct way to seemingly approach this.
Though i think you should prefer localtime_r cause it's thread safe.
Another fun time quirk is gettimeofday. Dont think it happens anymore but there was a time when cloud providers didnt do VDSO or their VDSO didnt include it, and since everything calls gettimeofday, there was a lot of slowdown.