我有一个非常简单的函数f :: Int -> Int
,我想为每个f
编写一个调用n = 1,2,...,max
的程序。每次调用f
后,应显示此时使用的(累计)时间(以及n
和f n
)。如何实施?
我仍然是Haskell中输入/输出的新手,所以这是我到目前为止所尝试的(使用一些玩具示例函数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
我不太清楚如何在这里介绍时间。 (Int
的{{1}}可能必须替换为其他内容。)
答案 0 :(得分:0)
你可能想要这样的东西。根据递归函数的需要调整以下基本示例。
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
取消注释最后一行以打印结果(它会很快变得非常大)。
答案 1 :(得分:0)
我终于找到了解决方案。在这种情况下,我们用毫秒来衡量“实际”时间。
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