最近因为工作接触到Nginx的学习,我就把Nginx的源代码下载下来,然后对其进行了分析。发现Nginx的性能强大离不开作者编码的苦心,作者将C的性能发挥到了极致,每个变量都用得非常出神入化。有如此强大的功能,才支撑了全球约一半的市场,
拿一个例子来说,之前我写过关于C获取时间的文章,那我就看Nginx是如何将表示时间的毫秒转换为具体的日期的。
下载之后找到src/core/ngx_times.c。
我将记录下来了
// ConsoleApplication1.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
//
#include <iostream>
typedef struct tm ngx_tm_t;
typedef intptr_t ngx_int_t;
void
ngx_gmtime(time_t t, ngx_tm_t* tp)
{
ngx_int_t sec, min, hour, mday, mon, year, wday, yday, days;
days = t / 86400;
/* Jaunary 1, 1970 was Thursday */
wday = (4 + days) % 7;
t %= 86400;
hour = t / 3600;
t %= 3600;
min = t / 60;
sec = t % 60;
/* the algorithm based on Gauss's formula */
days = days - (31 + 28) + 719527;
year = days * 400 / (365 * 400 + 100 - 4 + 1);
yday = days - (365 * year + year / 4 - year / 100 + year / 400);
mon = (yday + 31) * 12 / 367;
mday = yday - (mon * 367 / 12 - 31);
mon += 2;
if (yday >= 306) {
/*
* there is no "yday" in Win32 SYSTEMTIME
*
* yday -= 306;
*/
year++;
mon -= 12;
if (mday == 0) {
/* Jaunary 31 */
mon = 1;
mday = 31;
}
else if (mon == 2) {
if ((year % 4 == 0) && (year % 100 || (year % 400 == 0))) {
if (mday > 29) {
mon = 3;
mday -= 29;
}
}
else if (mday > 28) {
mon = 3;
mday -= 28;
}
}
/*
* there is no "yday" in Win32 SYSTEMTIME
*
* } else {
* yday += 31 + 28;
*
* if ((year % 4 == 0) && (year % 100 || (year % 400 == 0))) {
* yday++;
* }
*/
}
tp->tm_sec = (int)sec;
tp->tm_min = (int)min;
tp->tm_hour = (int)hour;
tp->tm_mday = (int)mday;
tp->tm_mon = (int)mon;
tp->tm_year = (int)year;
tp->tm_wday = (int)wday;
}
int main()
{
time_t t = time(NULL);
ngx_tm_t tp;
ngx_gmtime(t, &tp);
printf("%d年%d月%d日 %d时%d分%d秒", tp.tm_year, tp.tm_mon, tp.tm_mday, tp.tm_hour + 8, tp.tm_min, tp.tm_sec);
}
结果如下:
需要注意的是,生成的是UTC标准时间。