Created
September 29, 2012 18:01
-
-
Save malfet/3804734 to your computer and use it in GitHub Desktop.
Measuring 123456! evaluation time using various language constructs
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Text.Printf | |
import Control.Exception | |
import System.CPUTime | |
-- time function implementation borrowed from | |
-- http://www.haskell.org/haskellwiki/Timing_computations | |
time :: IO t -> IO t | |
time a = do | |
start <- getCPUTime | |
v <- a | |
end <- getCPUTime | |
let diff = (fromIntegral (end - start)) / (10^12) | |
printf "Computation time: %0.3f sec\n" (diff :: Double) | |
return v | |
-- Factorial implementations are from | |
-- "The Evolution of a Haskell Programmer" | |
-- http://www.willamette.edu/~fruehr/haskell/evolution.html | |
fac 0 = 1 | |
fac n = n * fac (n-1) | |
lim :: Integer | |
lim = 123456 | |
main = do | |
printf "Computing product [1..%d]\n" lim | |
time $ product [1..lim] `seq` return () | |
printf "Computing fac %d\n" lim | |
time $ fac lim `seq` return () | |
printf "Computing foldr (*) [1..%d]\n" lim | |
time $ foldr (*) 1 [1..lim] `seq` return () | |
printf "Computing foldl (*) [1..%d]\n" lim | |
time $ foldl (*) 1 [1..lim] `seq` return () | |
-- Below are programm output on 2.4Ghz Core i7 | |
-- $ ghc-7.4.2 -O3 facbench.hs ; ./facbench | |
-- [1 of 1] Compiling Main ( facbench.hs, facbench.o ) | |
-- Linking facbench ... | |
-- Computing product [1..123456] | |
-- Computation time: 1.726 sec | |
-- Computing fac 123456 | |
-- Computation time: 2.028 sec | |
-- Computing foldr (*) [1..123456] | |
-- Computation time: 7.270 sec | |
-- Computing foldl (*) [1..123456] | |
-- Computation time: 1.711 sec |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Maybe my problem was that I did not use optimization flags.