linux源码中的算法,Linux源码中的mktime算法解析

Linux源码中的mktime算法解析

我们知道,从CMOS中读出来的系统时间并不是time_t类型,而是类似于struct tm那样,年月日时分秒是分开存储的。

那么,要把它转化为系统便于处理的time_t类型,就需要算法进行转换。

我们都知道我们的公历还是比较复杂的,有大月小月,有闰年非闰年,处理起来会很麻烦。

但是Linux的源代码仅仅用了短短的几行就完成了这个复杂的转换(Gauss算法),实在令人惊奇。话不多说,先看源代码:

include/linux/time.h

70b68634ef1c8aa63d4ff1a34e8f9c21.png

static

inline

unsigned

long

mktime(

unsigned

int

year,

unsigned

int

mon,

70b68634ef1c8aa63d4ff1a34e8f9c21.png

unsigned

int

day,

unsigned

int

hour,

70b68634ef1c8aa63d4ff1a34e8f9c21.png

unsigned

int

min,

unsigned

int

sec)

b6a6a012886c150eec1bafc58a56a6c7.png

c386365ed6409a77a2cbcdadb3aeb713.png

...

{

e2f7ec2f38565e77cd88f2255780c98b.png

a6c6cd367ef50672abfd4eddd39f280b.pngif(0>=(int) (mon-=2))...{/**//* 1..12 -> 11,12,1..10 */e2f7ec2f38565e77cd88f2255780c98b.png

a6c6cd367ef50672abfd4eddd39f280b.png         mon+=12;/**//* Puts Feb last since it has leap day */a7597e26010f6241aab68b67e22f4c0d.png         year-=1;

4807b3a4d519e4f764c53724a411ee70.png    }a7597e26010f6241aab68b67e22f4c0d.png

a7597e26010f6241aab68b67e22f4c0d.pngreturn(((

a7597e26010f6241aab68b67e22f4c0d.png             (unsignedlong) (year/4-year/100+year/400+367*mon/12+day)+a7597e26010f6241aab68b67e22f4c0d.png             year*365-719499e2f7ec2f38565e77cd88f2255780c98b.png

a6c6cd367ef50672abfd4eddd39f280b.png          )*24+hour/**//* now have hours */e2f7ec2f38565e77cd88f2255780c98b.png

a6c6cd367ef50672abfd4eddd39f280b.png       )*60+min/**//* now have minutes */e2f7ec2f38565e77cd88f2255780c98b.png

a6c6cd367ef50672abfd4eddd39f280b.png    )*60+sec;/**//* finally seconds */e155cab07812f8f770fa4ceb5f541596.png}     看上去令人眼花缭乱,毫无头绪。下面就让我们对该算法作具体的分析。

先不看前面的,直接看return那句,该式整体上具有这样的结构:

T = ((X * 24 + hour) * 60 + min) * 60 + sec

这说明该算法是先算出从1970年1月1日开始的天数X,再进而求出具体的时间值T的。

因此我们重点看如何求天数X。也就是X = year/4 - year/100 + year/400 + 367*mon/12 + day + year*365 - 719499这一部分。

首先可以将上式拆成:

Y = year / 4 - year / 100 + year / 400

Z = 367 * mon / 12

W = year * 365 + day

X = Y + Z + W - 719499

Y很简单,它计算了从公元元年到所求年份为止所有的闰年数。从W式看出,该算法先假设所有年都是正常年(365天),再加上闰年额外的天数(式Y)。

到现在为止都算简单,关键是Z式和X式中的那个常数719499是怎么回事,似乎莫名其妙。还有就是它们和return语句前面的那个if判断有什么关系呢?

首先要澄清一点,常数719499并不是像很多人说的那样,是0001年1月1日到1970年1月1日所经历的天数。

不信你可以随手写个脚本,将得到正确的数字:719162天。

显然719162和719499是有关系的。我们把注意力放在那个if语句上:

70b68634ef1c8aa63d4ff1a34e8f9c21.png

mon

-=

2

;

b6a6a012886c150eec1bafc58a56a6c7.png

c386365ed6409a77a2cbcdadb3aeb713.png

if

(mon

<=

0

)

...

{

a7597e26010f6241aab68b67e22f4c0d.png    mon+=12;

a7597e26010f6241aab68b67e22f4c0d.png    year--;

e155cab07812f8f770fa4ceb5f541596.png}

很明显,它是想把1月和2月当作上一年年底的最后两个月,让3月作为一年的第一个月。这样一来,我们可以尽量少的被闰年所影响。

按照这个假设,让我们先不管Z式是怎么来的,看看0001年1月1日时,Y + Z + W等于什么:

mon = 1月变成上一年(公元前0001年)的11月;

year减一后变成了0,因此Y = 0;

Z = 367 * 11 / 12 = 336;

W = 1 + 0 * 365 = 1;

Y + Z + W = 337。

337这个数正好等于719499 - 719162!换句话说,它是对上述假设所做的补正!于是这些式子就变成了:

Y = year / 4 - year / 100 + year / 400

Z = 367 * mon / 12

V = Z - 337

W = year * 365 + day

X = Y + W + V - 719162

再来看式Z,这个式子表面看不出任何名堂,367这个数字显然很是奇怪。那让我们穷举一下mon,看看这个式子算出的都是些什么值吧:

mon         Z

1           30

2           61

3           91

4           122

5           152

6           183

7           214

8           244

9           275

10          305

11          336

12          367

似乎看出了什么?再让我们把相邻的两个mon的Z做一下减法看看:

mon         dZ

1           30

2           31

3           30

4           31

5           30

6           31

7           31

8           30

9           31

10          30

11          31

12          31

闻出点味道了吧,很象大小月的规则。让我们回想起那个if语句作了什么,它把1月2月变成了11月和12月,3月变成了1月!还原一下看看:

mon     org-mon         dZ

1       3               30

2       4               31

3       5               30

4       6               31

5       7               30

6       8               31

7       9               31

8       10              30

9       11              31

10      12              30

11      1               31

12      2               31

怎么本来应该是大月的3月成了30天?

那好我们想想这个原理,假设今天是1月1日,那你能说你今年已经过了31天了么?显然不是,1月还没过,我们不能把它算进去。

这里同然,我们从4月看起,如果今天是愚人节,那么距离3月1日我们经过了31天。

就像前面说的,我们假设一年是从3月开始,到次年的2月结束。按照这个规则,整个式子里有问题的只有3月,理论上这里应该是0!

但是这没关系,我们把它减去就行了,于是变成:

Z = 367 * mon / 12 - 30

V = Z - 307

回头看看W式,year * 365,但是按照上面的理论,没过完的这一年不应该加进去,所以这里把它减去,再和V式合并:

V = Z + 58

W = (year - 1) * 365 + day

我们记得这个算法的一年是从3月开始的,因此少算了公元元年的1月和2月的天数:31 + 28 = 59天:(公元元年是正常年)

V = Z + 59 - 1

那么最后的这个减1是什么?还是上面那个原理,今天还没过,就不应该把它算进去!

综上,整个算法就明朗了,主要难于理解的是那个3月开始的假设以及367 * mon / 12会产生类似大小月的序列。

最后把这些式子整理并罗列一下,做为本文的结束:

70b68634ef1c8aa63d4ff1a34e8f9c21.png

Y = (year - 1) * 365 + year / 4 - year / 100 + year / 400

70b68634ef1c8aa63d4ff1a34e8f9c21.png

M = 367 * mon / 12 - 30 + 59

70b68634ef1c8aa63d4ff1a34e8f9c21.png

D = day - 1

70b68634ef1c8aa63d4ff1a34e8f9c21.png

X = Y + M + D - 719162

70b68634ef1c8aa63d4ff1a34e8f9c21.png

T = ((X * 24 + hour) * 60 + min) * 60 + sec

static __time64_t __cdecl _make__time64_t ( struct tm *tb, int ultflag ) { __time64_t tmptm1, tmptm2, tmptm3; struct tm tbtemp; long dstbias = 0; long timezone = 0; _VALIDATE_RETURN( ( tb != NULL ), EINVAL, ( ( __time64_t )( -1 ) ) ) /* * First, make sure tm_year is reasonably close to being in range. */ if ( ((tmptm1 = tb->tm_year) _MAX_YEAR64 + 1) ) goto err_mktime; /* * Adjust month value so it is in the range 0 - 11. This is because * we don't know how many days are in months 12, 13, 14, etc. */ if ( (tb->tm_mon tm_mon > 11) ) { tmptm1 += (tb->tm_mon / 12); if ( (tb->tm_mon %= 12) tm_mon += 12; tmptm1--; } /* * Make sure year count is still in range. */ if ( (tmptm1 _MAX_YEAR64 + 1) ) goto err_mktime; } /***** HERE: tmptm1 holds number of elapsed years *****/ /* * Calculate days elapsed minus one, in the given year, to the given * month. Check for leap year and adjust if necessary. */ tmptm2 = _days[tb->tm_mon]; if ( _IS_LEAP_YEAR(tmptm1) && (tb->tm_mon > 1) ) tmptm2++; /* * Calculate elapsed days since base date (midnight, 1/1/70, UTC) * * * 365 days for each elapsed year since 1970, plus one more day for * each elapsed leap year. no danger of overflow because of the range * check (above) on tmptm1. */ tmptm3 = (tmptm1 - _BASE_YEAR) * 365 + _ELAPSED_LEAP_YEARS(tmptm1); /* * elapsed days to current month (still no possible overflow) */ tmptm3 += tmptm2; /* * elapsed days to current date. */ tmptm1 = tmptm3 + (tmptm2 = (__time64_t)(tb->tm_mday)); /***** HERE: tmptm1 holds number of elapsed days *****/ /* * Calculate elapsed hours since base date */ tmptm2 = tmptm1 * 24; tmptm1 = tmptm2 + (tmptm3 = (__time64_t)tb->tm_hour); /***** HERE: tmptm1 holds number of elapsed hours *****/ /* * Calculate elapsed minutes since base date */ tmptm2 = tmptm1 * 60; tmptm1 = tmptm2 + (tmptm3 = (__time64_t)tb->tm_min); /***** HERE: tmptm1 holds number of elapsed minutes *****/ /* * Calculate elapsed seconds since base date */ tmptm2 = tmptm1 * 60; tmptm1 = tmptm2 + (tmptm3 = (__time64_t)tb->tm_sec); /***** HERE: tmptm1 holds number of elapsed seconds *****/ if ( ultflag ) { /* * Adjust for timezone. No need to check for overflow since * localtime() will check its arg value */ __tzset(); _ERRCHECK(_get_dstbias(&dstbias;)); _ERRCHECK(_get_timezone(&timezone;)); tmptm1 += timezone; /* * Convert this second count back into a time block structure. * If localtime returns NULL, return an error. */ if ( _localtime64_s(&tbtemp;, &tmptm1;) != 0 ) goto err_mktime; /* * Now must compensate for DST. The ANSI rules are to use the * passed-in tm_isdst flag if it is non-negative. Otherwise, * compute if DST applies. Recall that tbtemp has the time without * DST compensation, but has set tm_isdst correctly. */ if ( (tb->tm_isdst > 0) || ((tb->tm_isdst 0)) ) { tmptm1 += dstbias; if ( _localtime64_s(&tbtemp;, &tmptm1;) != 0 ) goto err_mktime; } } else { if ( _gmtime64_s(&tbtemp;, &tmptm1;) != 0) goto err_mktime; } /***** HERE: tmptm1 holds number of elapsed seconds, adjusted *****/ /***** for local time if requested *****/ *tb = tbtemp; return tmptm1; err_mktime: /* * All errors come to here */ errno = EINVAL; return (__time64_t)(-1); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值