开发者

caching localtime_r() is it worth it?

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.


"Avoiding a library function call that's not really needed" is worth it, of couse. The rest is only your tradeoff between memory and speed.

Since you're calling this 3000/second, you might want to go even further and put this function as static inline in a header and also (if using GCC) use branch prediction hints for the conditional, stating that taking it is "unlikely":

if (__builtin_expect(now_sec != cache_sec, 0))
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜