我的计时器总是返回0 [英] My timer always returns 0

查看:190
本文介绍了我的计时器总是返回0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在haskell中创建了一个计时器。问题是,它总是返回0.我认为这是因为懒惰,但我不知道如何解决它。

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

正如您所见,我拥有抛出 seq $! galor,但无济于事。我在做什么?



在一个示例运行中:

  *主> timeit测试
你叫什么名字?
Haskell
您的名字是Haskell。
0.0


解决方案

工作

  import Data.Time.Clock 

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


$ b

现在进行一些讨论 -


  1. 从评论看来,你想要的是实时,而不是cpu时间,所以这就是我写的。

  2. System.Time库不推荐使用,所以我把你切换到了Data.Time库。
  3. NominalDiffTime保存时间,以秒为单位...


  4. NominalDiffTime忽略闰秒!如果在程序运行期间增加了闰秒,10秒延迟将显示为11秒。我搜索了如何解决这个问题,尽管Data.Time确实有一个DiffTime类型来解决这个问题,但似乎没有一种简单的方法可以根据UTCTime生成DiffTime。我想你可能可以使用Posix时间库,从1970年1月1日开始获得秒数......然后拿这个差异,但这看起来像是为了一个非常罕见的bug而喋喋不休。但是,如果您正在编写软件来安全降落飞机,请深入挖掘并修复此问题。 :)


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

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. :)

这篇关于我的计时器总是返回0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆