# \`hourglass\` Why use OS for \`dateTimeFromUnixEpoch\`?

**URL:** <https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557>\
**Category:** Learn\
**Created:** [July 26, 2025, 2:28pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557 "2025-07-26T14:28:29Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [July 26, 2025, 2:28pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/1 "2025-07-26T14:28:29Z")

</div>

`hourglass` has a function:

```haskell
dateTimeFromUnixEpoch :: Elapsed -> DateTime

```

where `Elapsed` is the number of seconds from the start of the Unix epoch on 1970-01-01 00:00:00 UTC and `DateTime` is a date and time (`YYYY-MM-DD hh:mm:ss`).

It implements that by making use of `gmtime_r` (Unix-like operating systems) and `FileTimeToSystemTime` (Windows). Neither of those C functions take account of leap seconds, so the underlying algorithms must be straightforward.

This my question: why would it do that? Why not implement the straightforward algorithm only in Haskell? Am I missing something?

The question arises because there is a TODO from May 2014 “pure haskell backup for dateTimeFromUnixEpoch” but that is expressed in terms of a ‘backup’.

---

<div class="post-metadata">

**Author:** ![rhendric](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/rhendric/32/2689_2.png) [@rhendric](https://discourse.haskell.org/u/rhendric)\
**Post date:** [July 26, 2025, 2:44pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/2 "2025-07-26T14:44:49Z")

</div>

> [@mpilgrem](#):
>
> Neither of those C functions take account of leap seconds

Are you sure? The glibc implementation of `gmtime_r` sure looks like it does. ([`__tz_convert`](https://sourceware.org/git/?p=glibc.git;a=blob;f=time/tzset.c;h=0ddc20328717bcf695de370cb48c83b06a7e076b;hb=HEAD#l567), called from [`gmtime.c`](https://sourceware.org/git/?p=glibc.git;a=blob;f=time/gmtime.c;h=ad6e8eb35233f6018607b938f303dc75323c8f6e;hb=HEAD))

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [July 26, 2025, 3:06pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/3 "2025-07-26T15:06:51Z")

</div>

I will double check. ChatGPT assured me - with repeated prompting - that it did not.

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [July 26, 2025, 4:17pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/4 "2025-07-26T16:17:04Z")

</div>

I think I needed to be more precise:

`hourglass-0.2.12` documents:

```haskell
-- | A number of seconds elapsed since the unix epoch.
newtype Elapsed = Elapsed Seconds
    deriving (Read,Eq,Ord,Num,Data,Typeable,NFData)

```

but it likely does not mean that. It likely means “A number of non-leap seconds since the Unix epoch”.

That is because POSIX has:

> A. Rationale for Base Definitions  
> A.4.19 Seconds Since the Epoch  
> Coordinated Universal Time (UTC) includes leap seconds. However, in POSIX time (seconds since the Epoch), leap seconds are ignored (not applied) to provide an easy and compatible method of computing time differences. Broken-down POSIX time is therefore not necessarily UTC, despite its appearance.  
> …it is inappropriate to require that a time represented as seconds since the Epoch precisely represent the number of seconds between the referenced time and the Epoch. …  
> The topic of whether seconds since the Epoch should account for leap seconds has been debated on a number of occasions, and each time consensus was reached (with acknowledged dissent each time) that the majority of users are best served by treating all days identically. (That is, the majority of applications were judged to assume a single length—as measured in seconds since the Epoch—for all days. Thus, leap seconds are not applied to seconds since the Epoch.).

As a consequence there are a few points in time, at the resolution of one second, (namely during leap seconds) that can’t be represented in POSIX time and a few UTC date and times (at that resolution) that don’t map to a unique number of non-leap seconds since the start of the Unix epoch.

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [July 30, 2025, 10:52pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/5 "2025-07-30T22:52:47Z")

</div>

I think I have answered my own question: “speed”. My pure Haskell alternative seems (based on `tasty-bench` output in GHCi 9.10.2 on x86\_64/Windows) to be about 15 to 30 times slower than Haskell calling the equivalent C functions provided by the OS. However, perhaps I am missing a trick? My latest version of the Haskell alternative looks like this:

```haskell
{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE NumericUnderscores #-}

{- |
Module : Time.Calendar.FromElapsed
License : BSD-style
Copyright : (c) 2025 Mike Pilgrem <public@pilgrem.com>
Stability : experimental
Portability : unknown

A native Haskell implementation of 'dateTimeFromUnixEpoch'.
-}

module Time.Calendar.FromElapsed
  ( dateTimeFromUnixEpoch
  ) where

import Data.Int ( Int64 )
import Time.Types
                   ( Date (..), DateTime (..), Elapsed (..), Hours (..)
                   , Minutes (..), Seconds (..), TimeOfDay (..)
                   )

dateTimeFromUnixEpoch :: Elapsed -> DateTime
dateTimeFromUnixEpoch (Elapsed (Seconds secs)) =
  if secs >= 0
    then afterUnixEpoch secs
    else beforeUnixEpoch (negate secs)
 where

  isleap :: Int -> Bool
  isleap !y =
    let isDivBy n = y `mod` n == 0
    in isDivBy 4 && not (isDivBy 100 || isDivBy 400)
  {-# INLINE isleap #-}

  days :: Int -> Int64
  days !y = if isleap y then 366 else 365
  {-# INLINE days #-}

  monthDays :: Bool -> Int -> Int64
  monthDays !isLeap !m = months !! m
   where
    months = if isLeap then leapMonths else nonLeapMonths
    leapMonths = [31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
    nonLeapMonths = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
  {-# INLINE monthDays #-}

  yearLoop :: Int -> Int -> Int64 -> (Int, Int64)
  yearLoop !dir !y !d =
    let yd = days y
    in if d <= yd
          then (y, d)
          else yearLoop dir (y + dir) (d - yd)

  monthLoop :: Bool -> Int -> Int -> Int64 -> (Int, Int64, Int64)
  monthLoop !isLeap !dir !m !d =
    let md = monthDays isLeap m
    in if d <= md
          then (m, d, md)
          else monthLoop isLeap dir (m + dir) (d - md)

  afterUnixEpoch :: Int64 -> DateTime
  afterUnixEpoch secs1 =
    let (!y, !m, !d, _, !h, !mi, !s) = fromUnixEpoch 1970 0 1 secs1
        date = Date y (toEnum m) (fromIntegral d + 1)
        tod = TimeOfDay (Hours h) (Minutes mi) (Seconds s) 0
    in DateTime date tod

  beforeUnixEpoch :: Int64 -> DateTime
  beforeUnixEpoch secs1 =
    let (!y, !m, !d, !md, !h, !mi, !s) = fromUnixEpoch 1969 11 (-1) secs1
        date = Date y (toEnum m) (fromIntegral $ md - d)
        tod = TimeOfDay (Hours (23 - h)) (Minutes (59 - mi)) (Seconds (60 - s)) 0
    in DateTime date tod

  fromUnixEpoch ::
       Int
    -> Int
    -> Int
    -> Int64
    -> (Int, Int, Int64, Int64, Int64, Int64, Int64)
  fromUnixEpoch !baseYear !baseMonth !dir !secs1 =
    let (!d1, !s1) = secs1 `quotRem` 86_400
        (!y, !d2) = yearLoop dir baseYear d1
        (!m, !d, !md) = monthLoop (isleap y) dir baseMonth d2
        (!h, !s2) = s1 `quotRem` 3_600
        (!mi, !s) = s2 `quotRem` 60
    in (y, m, md, d, h, mi, s)

```

---

<div class="post-metadata">

**Author:** ![Bodigrim](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/bodigrim/32/1457_2.png) [@Bodigrim](https://discourse.haskell.org/u/Bodigrim)\
**Post date:** [July 30, 2025, 11:29pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/6 "2025-07-30T23:29:38Z")

</div>

- Division is slow, use [quote-quot: Divide without division](https://hackage.haskell.org/package/quote-quot) as much as possible.
- `monthDays` should be something like `28 + (if isLeap then magic1 else magic2) `shiftR (2 * m) .&. 3.`

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [July 31, 2025, 12:31am UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/7 "2025-07-31T00:31:37Z")

</div>

Thanks! On reading around, I have also discovered that my loop-based approach to years is naive. I should, apparently, be making use of the ‘Gregorian proleptic epoch’ (0000-03-01) and the pattern of leap days after that, in blocks of 400 years.

---

<div class="post-metadata">

**Author:** ![VitWW](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/vitww/32/4184_2.png) [@VitWW](https://discourse.haskell.org/u/VitWW)\
**Post date:** [July 31, 2025, 12:57am UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/8 "2025-07-31T00:57:50Z")

</div>

> in blocks of 400 years.

in blocks of 100 and 400 years.  
In Julian Calendar leap year is every 4th year.

And you also forget, that in Julian Calendar 0th year does not exists: if we count down years, we have: 5, 4, 3, 2, 1, -1, -2, -3,…

UPD: Hm… And maybe it is better to return to Gregorian Calendar for big negative years to match tropical years with calendar ones.

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [July 31, 2025, 8:16pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/9 "2025-07-31T20:16:48Z")

</div>

With a better algorithm and straight-forward Haskell, I am down to 3 times slower than making use of what the OS provides. (Perhaps I should be satisfied with that. ChatGPT may be hallucinating, but it tells me the OS functions may use hand-optimised assembly.)

However, I am not having much luck with eliminating division by apeing `quote-quot`; that seems to halve, not increase, the speed of the better algorithm.

My straight-forward code now looks like this:

```haskell
module Time.Calendar.FromElapsed
  ( dateTimeFromUnixEpoch
  ) where

import Data.Int ( Int64 )
import Time.Types
                   ( Date (..), DateTime (..), Elapsed (..), Hours (..)
                   , Minutes (..), Seconds (..), TimeOfDay (..)
                   )

dateTimeFromUnixEpoch :: Elapsed -> DateTime
dateTimeFromUnixEpoch (Elapsed (Seconds secs)) =
  dateTimeFromGPEpoch (secs + 62_162_035_200)

-- | The \'Gregorian proleptic\' (GP) epoch (0000-03-01 00:00:00) follows a leap
-- day and starts a 400-year pattern of leap days.
dateTimeFromGPEpoch :: Int64 -> DateTime
dateTimeFromGPEpoch secs =
  let (!d1, !s1) = secs `quotRem` 86_400
      (!q400, !r400) = d1 `quotRem` 146_097
      (!q100, !r100) = r400 `minDivMod` 36_524
      (!q4, !r4) = r100 `quotRem` 1461
      (!q1, !r1) = r4 `minDivMod` 365
      !y' = fromIntegral $ 400 * q400 + 100 * q100 + 4 * q4 + q1
      !d2 = fromIntegral r1
      !isLeap = q1 == 0 && (q4 /= 0 || q100 == 0)
      (!m', !d) = monthDays isLeap d2
      (!h, !s2) = s1 `quotRem` 3_600
      (!mi, !s) = s2 `quotRem` 60
      (!y, !m) = if m' > 9 then (y' + 1, m' - 10) else (y', m' + 2)
      !date = Date y (toEnum m) d
      !tod = TimeOfDay (Hours h) (Minutes mi) (Seconds s) 0
  in DateTime { dtDate = date, dtTime = tod }
 where

  minDivMod :: Int64 -> Int64 -> (Int64, Int64)
  minDivMod !n !d =
    let (q, r) = n `quotRem` d
    in if q == 4 then (3, r + d) else (q, r)
  {-# INLINE minDivMod #-}

  -- | Month @0@ is March.
  monthDays :: Bool -> Int -> (Int, Int)
  monthDays !isLeap !doy = go 0 table
   where
    (table, febRef) = if isLeap then (leapTable, 337) else (nonLeapTable, 336)
    go !m (doy0 : doy1 : rest)
      | doy < doy1 = (m, doy - doy0 + 1)
      | otherwise = go (m + 1) (doy1 : rest)
    go _ _ = (11, doy - febRef) -- Fallback for February
    nonLeapTable = [0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337]
    leapTable = [0, 31, 62, 93, 123, 154, 185, 215, 246, 276, 307, 338]
  {-# INLINE monthDays #-}

```

That gives me:

```plaintext
> stack ghci --bench
ghci> defaultMain $ [bench "fromEpoch" $ nf Time.Calendar.dateTimeFromUnixEpoch (Elapsed 1753988346)]
All
  fromEpoch: OK
    16.3 μs ± 868 ns, 8.0 KB allocated, 0 B copied, 118 MB peak memory

```

My `quote-quot` inspired code (for example):

```plaintext
ghci> unType <$> (examineCode (quoteQuotRem (3600 :: Int64))) >>= putStrLn . pprint
\w_0 -> let q_1 = (\w_2 -> ((`GHC.Internal.Bits.shiftR` 10) GHC.Internal.Base.. ((`Numeric.QuoteQuot.mulHi` 5247073869855161349) GHC.Internal.Base.. GHC.Internal.Base.id)) w_2 GHC.Internal.Num.+ ((\w_3 -> GHC.Internal.Real.fromIntegral (GHC.Types.I# (GHC.Magic.dataToTag# (w_3 GHC.Classes.< 0)))) GHC.Internal.Base.. GHC.Internal.Base.id) w_2) w_0
         in (q_1, w_0 GHC.Internal.Num.- (3600 GHC.Internal.Num.* q_1))

```

looks like this:

```haskell
dateTimeFromGPEpoch :: Int64 -> DateTime
dateTimeFromGPEpoch secs =
  let (!d1, !s1) = quotRem86400 secs
      (!q400, !r400) = quotRem146097 d1
      (!q100, !r100) = minDivMod 36_524 quotRem36524 r400
      (!q4, !r4) = quotRem1461 r100
      (!q1, !r1) = minDivMod 365 quotRem365 r4
      !y' = fromIntegral $ 400 * q400 + 100 * q100 + 4 * q4 + q1
      !d2 = fromIntegral r1
      !isLeap = q1 == 0 && (q4 /= 0 || q100 == 0)
      (!m', !d) = monthDays isLeap d2
      (!h, !s2) = quotRem3600 s1
      (!mi, !s) = quotRem60 s2
      (!y, !m) = if m' > 9 then (y' + 1, m' - 10) else (y', m' + 2)
      !date = Date y (toEnum m) d
      !tod = TimeOfDay (Hours h) (Minutes mi) (Seconds s) 0
  in DateTime { dtDate = date, dtTime = tod }
 where

  minDivMod :: Int64 -> (Int64 -> (Int64, Int64)) -> Int64 -> (Int64, Int64)
  minDivMod !d !quotRemD !n =
    let (q, r) = quotRemD n
    in if q == 4 then (3, r + d) else (q, r)
  {-# INLINE minDivMod #-}

  monthDays :: Bool -> Int -> (Int, Int)
  monthDays !isLeap !doy = go 0 table
   where
    (table, febRef) = if isLeap then (leapTable, 337) else (nonLeapTable, 336)
    go !m (doy0 : doy1 : rest)
      | doy < doy1 = (m, doy - doy0 + 1)
      | otherwise = go (m + 1) (doy1 : rest)
    go _ _ = (11, doy - febRef) -- Fallback for February
    nonLeapTable = [0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337]
    leapTable = [0, 31, 62, 93, 123, 154, 185, 215, 246, 276, 307, 338]
  {-# INLINE monthDays #-}

  quotRem60 :: Int64 -> (Int64, Int64)
  quotRem60 = quotRemN2 60 5 (-8_608_480_567_731_124_087)
  {-# INLINE quotRem60 #-}

  quotRem365 :: Int64 -> (Int64, Int64)
  quotRem365 = quotRemN1 365 6 3_234_497_591_006_606_311
  {-# INLINE quotRem365 #-}

  quotRem1461 :: Int64 -> (Int64, Int64)
  quotRem1461 = quotRemN2 1_461 10 (-5_517_609_281_458_640_695)
  {-# INLINE quotRem1461 #-}

  quotRem3600 :: Int64 -> (Int64, Int64)
  quotRem3600 = quotRemN1 3_600 10 5_247_073_869_855_161_349
  {-# INLINE quotRem3600 #-}

  quotRem36524 :: Int64 -> (Int64, Int64)
  quotRem36524 = quotRemN2 36_524 15 (-1_896_998_432_287_073_591)
  {-# INLINE quotRem36524 #-}

  quotRem86400 :: Int64 -> (Int64, Int64)
  quotRem86400 = quotRemN1 86_400 13 1_749_024_623_285_053_783
  {-# INLINE quotRem86400 #-}

  quotRem146097 :: Int64 -> (Int64, Int64)
  quotRem146097 = quotRemN1 146_097 15 4_137_408_090_565_272_301
  {-# INLINE quotRem146097 #-}

  quotRemN1 :: Int64 -> Int -> Int64 -> Int64 -> (Int64, Int64)
  quotRemN1 !n !rShift !magic !w_0 =
    let q = w2 w_0
        w2 w_2 = ((`shiftR` rShift) . (`mulHiInt64` magic)) w_2 + w3 w_2
        w3 w_3 = fromIntegral (I# (dataToTag# (w_3 < 0)))
    in (q, w_0 - (n * q))
  {-# INLINE quotRemN1 #-}

  quotRemN2 :: Int64 -> Int -> Int64 -> Int64 -> (Int64, Int64)
  quotRemN2 !n !rShift !magic !w_0 =
    let q = w2 w_0
        w2 w_2 = ((`shiftR` rShift) . w3) w_2 + w4 w_2
        w3 w_3 = w_3 + (`mulHiInt64` magic) w_3
        w4 w_4 = fromIntegral (I# (dataToTag# (w_4 < 0)))
    in (q, w_0 - (n * q))
  {-# INLINE quotRemN2 #-}

  mulHiInt64 :: Int64 -> Int64 -> Int64
  mulHiInt64 x y = fromIntegral (fromIntegral x `mulHiInt` fromIntegral y :: Int)
  {-# INLINE mulHiInt64 #-}

  mulHiInt :: Int -> Int -> Int
  mulHiInt (I# x) (I# y) = let !(# _, hi, _ #) = timesInt2# x y in I# hi
  {-# INLINE mulHiInt #-}

```

That gives me (and I think it makes use of things not available on 32-bit machines):

```plaintext
ghci> defaultMain $ [bench "fromEpoch" $ nf Time.Calendar.dateTimeFromUnixEpoch (Elapsed 1753988346)]
All
  fromEpoch: OK
    37.2 μs ± 2.6 μs, 20 KB allocated, 1 B copied, 119 MB peak memory

```

---

<div class="post-metadata">

**Author:** ![arybczak](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/arybczak/32/2527_2.png) [@arybczak](https://discourse.haskell.org/u/arybczak)\
**Post date:** [July 31, 2025, 8:20pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/10 "2025-07-31T20:20:39Z")

</div>

Why is using existing C functions a problem? 🤔

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [July 31, 2025, 8:24pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/11 "2025-07-31T20:24:58Z")

</div>

The short answer is, it is not a problem. This started off as a ponder, and ended up as a voyage of discovery on my part.

Now I understand why `hourglass` is ‘performant’ (it cheats), I am not planning to change anything.

---

<div class="post-metadata">

**Author:** ![VitWW](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/vitww/32/4184_2.png) [@VitWW](https://discourse.haskell.org/u/VitWW)\
**Post date:** [August 1, 2025, 1:32pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/12 "2025-08-01T13:32:49Z")

</div>

Some tricks to save calculations:

- only those, which is not divisible by 4, are also not divisible by 100.
- only those, which is not divisible by 100, are also not divisible by 400.

---

<div class="post-metadata">

**Author:** ![viktor](https://avatars.discourse-cdn.com/v4/letter/v/d6d6ee/32.png) [@viktor](https://discourse.haskell.org/u/viktor)\
**Post date:** [August 2, 2025, 1:38pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/13 "2025-08-02T13:38:26Z")

</div>

Efficient conversion of 64-bit Unix epoch time to proleptic Gregorian time (year 1 preceded by year 0 rather than `-1`):

```haskell
import Data.Int (Int64)
import Data.Word (Word8)

data Date = Date 
    { year :: !Int64
    , month :: !Word8
    , mday :: !Word8
    , hour :: !Word8
    , mins :: !Word8
    , secs :: !Word8
    }
  deriving (Eq, Ord, Show)

-- | 64-bit epoch to proleptic Gregorian date, based on
-- <http://howardhinnant.github.io/date_algorithms.html>
--
proleptic :: Int64 -> Date
proleptic t = Date { year = yr
                   , month = fromIntegral mn
                   , mday = fromIntegral dy
                   , hour = fromIntegral hh
                   , mins = fromIntegral mm
                   , secs = fromIntegral ss }
  where
    (!z0, !s) = t `divMod` 86400
    !z = z0 + 719468
    (!era, !doe) = z `divMod` 146097
    !yoe = (doe - doe `quot` 1460 + doe `quot` 36524
               - doe `quot` 146096) `quot` 365
    !y = yoe + era * 400
    !doy = doe - (365*yoe + yoe `quot` 4 - yoe `quot` 100)
    !mp = (5*doy + 2) `quot` 153
    !dy = doy - (153*mp + 2) `quot` 5 + 1
    !mn = 1 + (mp + 2) `rem` 12
    !yr = y + (12 - mn) `quot` 10
    (!hh, (!mm, !ss)) = flip divMod 60 <$> s `divMod` 3600

```

---

<div class="post-metadata">

**Author:** ![Bodigrim](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/bodigrim/32/1457_2.png) [@Bodigrim](https://discourse.haskell.org/u/Bodigrim)\
**Post date:** [August 2, 2025, 3:37pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/14 "2025-08-02T15:37:10Z")

</div>

> [@mpilgrem](#):
>
> However, I am not having much luck with eliminating division by apeing `quote-quot`; that seems to halve, not increase, the speed of the better algorithm.

> [@mpilgrem](#):
>
> ```haskell
> > stack ghci --bench
> ghci> defaultMain $ [bench "fromEpoch" $ nf Time.Calendar.dateTimeFromUnixEpoch (Elapsed 1753988346)]
> All
> fromEpoch: OK
> 16.3 μs ± 868 ns, 8.0 KB allocated, 0 B copied, 118 MB peak memory
> 
> ```

Am I reading it correct that you are benchmarking bytecode execution in `ghci`? This is unlikely to serve a good proxy for performance of compiled code.

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [August 2, 2025, 5:45pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/15 "2025-08-02T17:45:30Z")

</div>

Thanks! I see, first, that I made a mistake with my ‘better’ algorithm. Even on its own terms, it should have had:

```haskell
  monthDays :: Int -> (Int, Int)
  monthDays !doy = go 0 [0, 31, 61, 92, 122, 153, 184, 214, 245, 275, 306, 337]
   where
    go !i (a : b : rest)
      | doy < b = (i, doy - a + 1)
      | otherwise = go (i + 1) (b : rest)
    go _ _ = (11, doy - 336) -- Fallback for February
  {-# INLINE monthDays #-}

```

Second, I see your alternative avoids a ‘look up’ by making use of the relationship:

```plaintext
> map (\m -> (153 * m + 2) `quot` 5) ([0 .. 11] :: [Int])
[0,31,61,92,122,153,184,214,245,275,306,337]

```

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [August 2, 2025, 11:29pm UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/16 "2025-08-02T23:29:27Z")

</div>

You are, of course, correct. I created a benchmark in the package (for 1 Mar 2024 (start of year) and 29 Feb 2024 (end of year)) and tried again, with very different results (ns, not μs):

| Version | Windows 11 | Ubuntu 24.01.1 (via WSL 2) |
| --- | --- | --- |
| Call out to OS | 298/295 | 137/139 |
| Haskell (lookup) | 83/124 | 81/118 |
| Haskell (all math; no lookup) | 94/96 | 93/92 |
| Haskell (quote-quot) | 31/30 | 27/28 |

---

<div class="post-metadata">

**Author:** ![viktor](https://avatars.discourse-cdn.com/v4/letter/v/d6d6ee/32.png) [@viktor](https://discourse.haskell.org/u/viktor)\
**Post date:** [August 3, 2025, 4:57am UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/17 "2025-08-03T04:57:21Z")

</div>

Are you willing to share a link to the benchmark code?

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [August 3, 2025, 9:12am UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/18 "2025-08-03T09:12:38Z")

</div>

On sharing code, certainly:

There are four (temporary) branches at:

- [GitHub - mpilgrem/time-hourglass: efficient and simpler time API for haskell](https://github.com/mpilgrem/time-hourglass)

that build one upon the other. They are, in order:

- `fromEpoch-bench`, that adds a `bench-fromEpoch` benchmark for the existing code
- `fromEpoch`, that uses Haskell (lookup) and extends that benchmark;
- `fromEpoch-no-lookup`, that uses Haskell (all math; no lookup); and
- `fromEpoch-quote-quot`, that is inspired by `quote-quot`.

The benchmark looks like this:

```haskell
{-# LANGUAGE NumericUnderscores #-}

module Main
  ( main
  ) where

import qualified Time.Calendar as C
import qualified Time.Calendar.FromElapsed as FE
import Test.Tasty.Bench ( bench, bgroup, defaultMain, nf )

main :: IO ()
main = defaultMain
  [ bgroup "fromEpoch (Time.Calendar)" $
      [ bench "2024-03-01" $ nf C.dateTimeFromUnixEpoch 1_709_337_599
      , bench "2024-02-29" $ nf C.dateTimeFromUnixEpoch 1_709_251_199
      ]
  , bgroup "fromEpoch (Time.Calendar.FromElapsed)" $
      [ bench "2024-03-01" $ nf FE.dateTimeFromUnixEpoch 1_709_337_599
      , bench "2024-02-29" $ nf FE.dateTimeFromUnixEpoch 1_709_251_199
      ]
  ]

```

---

<div class="post-metadata">

**Author:** ![Bodigrim](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/bodigrim/32/1457_2.png) [@Bodigrim](https://discourse.haskell.org/u/Bodigrim)\
**Post date:** [August 3, 2025, 9:20am UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/19 "2025-08-03T09:20:18Z")

</div>

Just curious: is there a reason you avoid using `quote-quot` directly?

---

<div class="post-metadata">

**Author:** ![mpilgrem](https://sea2.discourse-cdn.com/flex002/user_avatar/discourse.haskell.org/mpilgrem/32/2529_2.png) [@mpilgrem](https://discourse.haskell.org/u/mpilgrem)\
**Post date:** [August 3, 2025, 9:25am UTC](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557/20 "2025-08-03T09:25:28Z")

</div>

I have not been using `quote-quot` directly because I wanted to avoid a direct dependency on `template-haskell` and I was only substituting a small number of divisions.

EDIT: Testing, I found another reason: the `quote-quot` package does not provide a `MulHi` instance for `Int64` before `base-4.15.0.0` (GHC 9.0.1), so I handspun:

```haskell
#if MIN_VERSION_base(4,15,0)
  mulHiInt :: Int -> Int -> Int
  mulHiInt (I# x) (I# y) = let !(# _, hi, _ #) = timesInt2# x y in I# hi
  {-# INLINE mulHiInt #-}
#else
  mulHiInt :: Int -> Int -> Int
  mulHiInt 0 _ = 0
  mulHiInt _ 0 = 0
  mulHiInt x y
    | x < 0, y > 0 = mulHiIntPos True (negate x) y
    | x > 0, y < 0 = mulHiIntPos True x (negate y)
    | otherwise = mulHiIntPos False x y
  {-# INLINE mulHiInt #-}

  -- | x# and y# are known to be positive.
  mulHiIntPos :: Bool -> Int -> Int -> Int
  mulHiIntPos isNeg (I# x#) (I# y#) =
    let wx# = int2Word# x#
        wy# = int2Word# y#
        !(# high#, low# #) = timesWord2# wx# wy#
        lowC# = plusWord# (not# low#) 1##
        highC# = plusWord# (not# high#) (int2Word# (lowC# `eqWord#` 0##))
    in I# (word2Int# (if isNeg then highC# else high#))
  {-# INLINE mulHiIntPos #-}
#endif

```

[Next page](https://discourse.haskell.org/t/hourglass-why-use-os-for-datetimefromunixepoch/12557.md?page=2)
