Skip to content

Instantly share code, notes, and snippets.

@monadplus
Created August 10, 2022 17:26
Show Gist options
  • Save monadplus/3fea11906c5ed28c16c07a4696d0ad1e to your computer and use it in GitHub Desktop.
Save monadplus/3fea11906c5ed28c16c07a4696d0ad1e to your computer and use it in GitHub Desktop.
Haskell: be careful when measuring elapsed time
-- | >>> measure (return $ sum [1..100000000])
-- (5000000050000000,1.892e-6)
measure :: IO a -> IO (a, Double)
measure io = do
start <- getMonotonicTimeNSec
a <- io
end <- getMonotonicTimeNSec
return (a, fromIntegral (end - start) / 1_000_000_000)
-- | >>> measure (return $ sum [1..100000000])
-- (5000000050000000,1.329306812)
measure' :: NFData a => IO a -> IO (a, Double)
measure' io = do
start <- getMonotonicTimeNSec
a <- io
end <- a `deepseq` getMonotonicTimeNSec
return (a, fromIntegral (end - start) / 1_000_000_000)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment