Skip to content

Instantly share code, notes, and snippets.

@markhibberd
Created October 2, 2014 04:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save markhibberd/5a7d15f76f3d48b2ec0e to your computer and use it in GitHub Desktop.
Save markhibberd/5a7d15f76f3d48b2ec0e to your computer and use it in GitHub Desktop.
{-# LANGUAGE OverloadedStrings #-}
{-# LANGUAGE TemplateHaskell #-}
-- FIX de-dupe with apiengine-server
module Apiengine.Trace.Duration (
Duration
, durationToMicro
, microToDuration
, durationToDiffTime
, diffTimeToDuration
) where
import Apiengine.Trace.Prelude
import Data.Aeson
import Data.Time
-- | Duration with microsecond accuracy, any additional precision is ignored,
newtype Duration =
Duration {
getDuration :: DiffTime
} deriving (Eq, Show)
durationToMicro :: Duration -> Integer
durationToMicro =
truncate . (fromIntegral (1000000 :: Integer) *) . toRational . getDuration
microToDuration :: Integer -> Duration
microToDuration =
Duration . picosecondsToDiffTime . (1000000 *) . abs
durationToDiffTime :: Duration -> DiffTime
durationToDiffTime =
getDuration
diffTimeToDuration :: DiffTime -> Duration
diffTimeToDuration =
microToDuration . durationToMicro . Duration
instance FromJSON Duration where
parseJSON = withNumber "Duration" $ return . microToDuration . floor
instance ToJSON Duration where
toJSON = Number . fromIntegral . durationToMicro
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment