My timer always returns 0

2019-07-02 09:41发布

问题:

I have created a timer in haskell. The problem is, it always returns 0. I think this is because of laziness, but I do not know how to fix it.

import System.CPUTime
timeit::IO ()->IO (Float)
timeit io=do
    start  <-getCPUTime
    action <-seq start io
    end    <-seq action getCPUTime
    return $! (fromIntegral $ end-start)/(10**12)

As you can see, I have throw in seq and $! galor, but to no avail. What do I do?

Here in an example run:

*Main> timeit test
What is your name?
Haskell
Your name is Haskell.
0.0

回答1:

Here is some code I got to work

import Data.Time.Clock

timeit::IO ()->IO NominalDiffTime
timeit doit=do
    start  <- getCurrentTime
    doit
    end    <- getCurrentTime
    return (diffUTCTime end start)

Now for some discussion-

  1. From the comments it seemed that you wanted real time, not cpu time, so that is what I wrote.

  2. The System.Time libary is deprecated, so I switched you to the Data.Time library.

  3. NominalDiffTime holds the time in seconds....

  4. NominalDiffTime ignores leap seconds! In the unlikely event that a leap second is added during the running of the program, a 10 second delay will show up as 11 seconds. I googled around on how to fix this, and although Data.Time does have a DiffTime type to account for this, there doesn't seem to be a simple way to generate a DiffTime from UTCTime. I think you may be able to use the Posix time libraries and get seconds from Jan 1, 1970.... Then take the diff, but this seems like to much hastle for a pretty rare bug. If you are writing software to safely land airplanes however, please dig a bit deeper and fix this problem. :)



回答2:

I've used this before and it works well for approximations. Don't rely on it for very precise times, but it should be accurate to within a millisecond. I've never tested its accuracy, so use at your own risk

import System.CPUTime

timeit :: IO a -> IO (a, Integer)
timeit action = do
    start <- getCPUTime
    value <- action
    end   <- getCPUTime
    return (value, end - start)

No explicit strictness required.



标签: haskell timer