4 ms·
Do you mean the conversion from YYYY-MM-DD to Unix Time? That can be quite fast; I wrote a blog article showing some algorithms that take less than 10ns to per
by haberman 3y ago
Do you mean the conversion from YYYY-MM-DD to Unix Time? That can be quite fast; I wrote a blog article showing some algorithms that take less than 10ns to perform the conversion: https://blog.reverberate.org/2020/05/12/optimizing-date-algorithms.html https://blog.reverberate.org/2020/05/12/optimizing-date-algo...
Recently I came across another variant of the algorithm that is even smaller and simpler. I've been meaning to test this variant and add it to my article (assuming it is correct), but I haven't had the chance: https://dotat.at/@/2008-09-10-counting-the-days.html https://dotat.at/@/2008-09-10-counting-the-days.html. (EDIT: I just tried it out. It works, and while the source code is smaller than my other variants, epoch_days_fast() from my article is still smaller and faster in terms of machine code: https://godbolt.org/z/Kjnafzqcx https://godbolt.org/z/Kjnafzqcx vs https://godbolt.org/z/e7nchjKGW https://godbolt.org/z/e7nchjKGW)
- dmw_ng 3y agoAmazing work :) Do you know if glibc gmtime_r() might be impacted by the active timezone? My "massively expensive" experience above came from gmtime_r() on Amazon Linux running in Lambda, but I can't remember the exact scenario involved (or e.g. if TZ were set), it certainly seems unlikely worth putting the effort into it that I did if the costs were similar to those observed in your post.
- haberman 3y agoThanks! I didn't experiment with gmtime_r() since it goes in the other direction (UnixTime -> civil time). I wouldn't expect timegm() or gmtime_r() to depend on current timezone, since both are hard-coded to use UTC. I never did figure out why the macOS version is performing mutex locks on global data.
- kccqzy 3y agoThat's amazing! Long time ago I wrote a conversion function that took longer than 10ns but had the input normalization feature you skipped in your blog post. (Say January 32nd will be automatically transformed to February 1st, and specifying the thirteenth month of a year will become January of the following year.) Those are simple to implement and I doubt it costs much. To normalize months outside of the 1–12 range: --month; if (month >= 12 || month < 0) { year += month / 12; month %= 12; if (month < 0) { --year; month += 12; } } ++month; To fix incorrect days that's even easier. Most algorithms do not need any changes.