功能重复计时

Repeated timing of function

我有一个非常简单的函数 f :: Int -> Int,我想编写一个程序为每个 n = 1,2,...,max 调用 f。在每次调用 f 之后,应显示到该点为止使用的(累积)时间(以及 nf n)。如何实施?

我在 Haskell 中对 input/output 还是很陌生,所以这是我到目前为止尝试过的方法(使用一些玩具示例函数 f

f :: Int -> Int
f n = sum [1..n]

evalAndTimeFirstN :: Int -> Int -> Int -> IO()
evalAndTimeFirstN n max time = 
  if n == max 
   then return () -- in the following we have to calculate the time difference from start to now
   else let str =  ("(" ++ (show n) ++  ", " ++ (show $ f n) ++ ", "++ (show time)++ ")\n") 
         in putStrLn str >> evalAndTimeFirstN (n+1) max time -- here we have to calculate the time difference

main :: IO()
main = evalAndTimeFirstN 1 5 0

我不太明白我要在这里介绍时间。 (timeInt 可能必须用其他东西替换。)

您可能想要这样的东西。根据递归函数的需要调整以下基本示例。

import Data.Time.Clock
import Control.Exception (evaluate)

main :: IO ()
main = do
  putStrLn "Enter a number"
  n <- readLn
  start <- getCurrentTime
  let fact = product [1..n] :: Integer
  evaluate fact  -- this is needed, otherwise laziness would postpone the evaluation
  end <- getCurrentTime
  putStrLn $ "Time elapsed: " ++ show (diffUTCTime end start)
  -- putStrLn $ "The result was " ++ show fact

取消最后一行的注释以打印结果(它很快就会变得非常大)。

我终于找到了解决办法。在这种情况下,我们以毫秒为单位测量 "real" 时间。

import Data.Time
import Data.Time.Clock.POSIX

f n = sum[0..n]

getTime = getCurrentTime >>= pure . (1000*) . utcTimeToPOSIXSeconds >>= pure . round

main = do 
    maxns <- getLine 
    let maxn = (read maxns)::Int
    t0 <- getTime 
    loop 1 maxn t0
     where loop n maxn t0|n==maxn = return ()
           loop n maxn t0
             = do 
                 putStrLn $ "fun eval: " ++ (show n) ++ ", " ++ (show $ (f n)) 
                 t <- getTime
                 putStrLn $ "time: " ++ show (t-t0); 
                 loop (n+1) maxn t0