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
Here is some code I got to work
Now for some discussion-
From the comments it seemed that you wanted real time, not cpu time, so that is what I wrote.
The System.Time libary is deprecated, so I switched you to the Data.Time library.
NominalDiffTime holds the time in seconds....
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. :)
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
No explicit strictness required.