简体   繁体   English

strftime性能与snprintf

[英]strftime performance vs. snprintf

I have run into an interesting performance conundrum but before I start delving into glibc and entering bugs left right and center I just wanted to get to get any insight that might be out there. 我遇到了一个有趣的性能难题,但是在我开始研究glibc并从左到右输入错误之前,我只是想获得任何可能的见解。

I have code that in one of the functions does this: 我在其中一个函数中执行以下操作的代码:

gettimeofday( &tv, 0);
localtime_r( &tv.tv_sec, &local_tm );
char result[25];
strftime( result, 24, "%Y-%m-%d %H:%M:%S", &local_tm);

The rest of the code is irrelevant for this question. 其余代码与该问题无关。 When I replace it with this: 当我用这个替换它时:

gettimeofday( &tv, 0);
localtime_r( &tv.tv_sec, &local_tm );
char result[25];
snprintf(result, sizeof(result), "%04d-%02d-%02d %02d:%02d:%02d",
         local_tm.tm_year+1900, local_tm.tm_mon+1,
         local_tm.tm_mday, local_tm.tm_hour, local_tm.tm_min,
         local_tm.tm_sec);

on average I get 20% performance boost. 平均而言,我可以获得20%的性能提升。

Has anyone ran into this? 有人遇到过这个吗? Is this OS specific? 这个操作系统是特定的吗?

POSIX requires strftime to call tzset() (or act as if it did), which on a linux system will likely stat /etc/timezone and other files, which is slow (compared to snprintf). POSIX要求strftime调用tzset() (或像执行该操作一样),在Linux系统上它可能会统计/ etc / timezone和其他文件,这很慢(与snprintf相比)。 Setting the TZ environment variable will generally give it a great boost. 设置TZ环境变量通常会大大提高它。

As was said in the comments it also localizes the message. 如评论中所说,它还可以对消息进行本地化。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM