为什么 gmtime 以这种方式实现? [英] Why is gmtime implemented this way?

查看:41
本文介绍了为什么 gmtime 以这种方式实现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我偶然发现了 Minix 的 gmtime 函数的源代码.我对从纪元以来的天数计算年份数的位感兴趣.这是那一点的胆量:

I happened across the source for Minix's gmtime function. I was interested in the bit that calculated the year number from days since epoch. Here are the guts of that bit:

http://www.raspberryginger.com/jbailey/minix/html/gmtime_8c-source.html

http://www.raspberryginger.com/jbailey/minix/html/loc__time_8h-source.html

#define EPOCH_YR 1970
#define LEAPYEAR(year) (!((year) % 4) && (((year) % 100) || !((year) % 400)))
#define YEARSIZE(year) (LEAPYEAR(year) ? 366 : 365)

int year = EPOCH_YR;

while (dayno >= YEARSIZE(year)) {
    dayno -= YEARSIZE(year);
    year++;
}

看起来算法是 O(n),其中 n 是与 epoch 的距离.此外,似乎必须为每一年单独计算 LEAPYEAR -ndash;当前日期的数十次,以及未来很远的日期的更多次.我有以下算法来做同样的事情(在这种情况下来自 ISO-9601 时代(0 = 1 BC)而不是 UNIX 时代):

It looks like the algorithm is O(n), where n is the distance from the epoch. Additionally, it seems that LEAPYEAR must be calculated separately for each year – dozens of times for current dates and many more for dates far in the future. I had the following algorithm for doing the same thing (in this case from the ISO-9601 epoch (Year 0 = 1 BC) rather than UNIX epoch):

#define CYCLE_1   365
#define CYCLE_4   (CYCLE_1   *  4 + 1)
#define CYCLE_100 (CYCLE_4   * 25 - 1)
#define CYCLE_400 (CYCLE_100 *  4 + 1)

year += 400 * (dayno / CYCLE_400)
dayno = dayno % CYCLE_400

year += 100 * (dayno / CYCLE_100)
dayno = dayno % CYCLE_100

year +=   4 * (dayno / CYCLE_4)
dayno = dayno % CYCLE_4

year +=   1 * (dayno / CYCLE_1)
dayno = dayno % CYCLE_1

这对于任何日期都以 O(1) 运行,看起来即使对于合理接近 1970 年的日期也应该更快.

This runs in O(1) for any date, and looks like it should be faster even for dates reasonably close to 1970.

那么,假设 Minix 开发人员是聪明人,他们这样做是有原因的,并且可能比我更了解 C,为什么?

So, assuming that the Minix developers are Smart People who did it their way for a Reason, and probably know a bit more about C than I do, why?

推荐答案

这纯粹是推测,但也许 MINIX 有比执行速度更重要的要求,例如简单、易于理解和简洁?毕竟,有些代码印在教科书中.

This is pure speculation, but perhaps MINIX had requirements that were more important than execution speed, such as simplicity, ease of understanding, and conciseness? Some of the code was printed in a textbook, after all.

这篇关于为什么 gmtime 以这种方式实现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆