Linux源码中的mktime算法解析
我们知道,从CMOS中读出来的系统时间并不是time_t类型,而是类似于struct tm那样,年月日时分秒是分开存储的。
那么,要把它转化为系统便于处理的time_t类型,就需要算法进行转换。
我们都知道我们的公历还是比较复杂的,有大月小月,有闰年非闰年,处理起来会很麻烦。
但是Linux的源代码仅仅用了短短的几行就完成了这个复杂的转换(Gauss算法),实在令人惊奇。话不多说,先看源代码:
include/linux/time.h
static
inline
unsigned
long
mktime
(
unsigned
int
year,
unsigned
int
mon,
unsigned
int
day,
unsigned
int
hour,
unsigned
int
min
,
unsigned
int
sec)
{
if
(
0 >
=
(
int
)
(
mon -
=
2)
)
{
/**/
/* 1..12 -> 11,12,1..10 */
mon +
=
12;
/**/
/* Puts Feb last since it has leap day */
year -
=
1;
}
return
(
(
(
(
unsigned
long
)
(
year/
4 -
year/
100 +
year/
400 +
367*
mon/
12 +
day)
+
year*
365 -
719499
)
*
24 +
hour /**/
/* now have hours */
)
*
60 +
min
/**/
/* now have minutes */
)
*
60 +
sec;
/**/
/* finally seconds */
}
看上去令人眼花缭乱,毫无头绪。下面就让我们对该算法作具体的分析。
先不看前面的,直接看return那句,该式整体上具有这样的结构:
T = ((X * 24 + hour) * 60 + min) * 60 + sec
这说明该算法是先算出从1970年1月1日开始的天数X,再进而求出具体的时间值T的。
 
相关文档:
ls
ls 命令可以说是linux下最常用的命令之一。它有众多的选项,其中有很多是很有用的,你是否熟悉呢?下面列出了 ls 命令的绝大多数选项。
-a 列出目录下的所有文件,包括以 . 开头的隐含文件。
-b 把文件名中不可输出的字符用反斜杠加字符编号(就象在C语言里一样)的形式列出。
-c 输出文件的 i 节 ......
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <sys/ioctl.h>
#include <net/if.h>
#include <stdio.h>
#include <string>
#include <iostream>
#include <cstring>
using namespace std;
void peek_interfaces(int ......
·find path -option [ -print ] [ -exec -ok command ] {} \;
#-print 将查找到的文件输出到标准输出
#-exec command {} \; -----将查到的文件执行command操作,{} 和 \;之间有空格
#-ok 和-exec相同,只不过在操作前要询 ......
<!--
@page { margin: 2cm }
P { margin-bottom: 0.21cm }
-->
Linux
世界很精彩,令人眼花缭乱。近期以来,各种轻型
Linux
版本不断登台亮相,知名的
Puppy
(小狗之名)便是一例。何故?
......