is it worth keeping a local copy of struct tm and update it only when required; below func is not thread safe… also I’ve seen only 6 to 7% of CPU time can be saved…
struct tm* custom_localtime (time_t now_sec)
{
static time_t cache_sec;
static struct tm tms;
if (now_sec != cache_sec) {
cache_sec = now_sec;
localtime_r(&cache_sec, &(tms));
}
return(&tms);
}
Additional details:
– my app makes more than 3000/sec calls to localtime_r()
found out at least 33% CPU time saving when I cache time-stamp strings of the format "2011-12-09 10:32:45" againt time_t seconds
thank you all nos, asc99c and Mircea.
I would probably have mentioned the 3000/s call rate in your question! Do it. I recently was profiling generation of a screen which was calling localtime approx 1,000,000 * 10,000 times.
The nested loops could have been improved substantially with a bit of thought, but what I saw was about 85% of CPU time was used by localtime. Simply caching the result so it was only called 10,000 times cut 85% of the time off page generation, and that made it easily fast enough.