Ticket #3245: CastSpeed.hs

File CastSpeed.hs, 1.0 KB (added by guest, 5 years ago)

Example code showing performance problem

Line 
1{-# LANGUAGE ExistentialQuantification #-}
2
3import Data.Typeable
4import Data.Maybe
5import System.CPUTime
6import System.Environment
7import Unsafe.Coerce
8
9data Any = forall a. (Typeable a) => Any a
10
11sum1 :: [Any] -> Int
12sum1 [] = 0
13sum1 (Any x:xs) = (fromJust (cast x) :: Int) + sum1 xs
14
15sum2 :: [Any] -> Int
16sum2 [] = 0
17sum2 (Any x:xs) = head (fromJust (cast x) :: [Int]) + sum2 xs
18
19sum3 :: [Any] -> Int
20sum3 [] = 0
21sum3 (Any x:xs) = head (unsafeCoerce x :: [Int]) + sum3 xs
22
23doTime x = do
24  start <- getCPUTime
25  putStr "Result: "
26  print x
27  stop <- getCPUTime
28  putStr "Time(sec): "
29  print (fromIntegral (stop - start) / 1e12)
30
31main = do
32  [len] <- getArgs
33  let list = [1..read len::Int]
34  putStrLn "sum1"
35  let x = map Any list
36  doTime $ sum1 x
37  doTime $ sum1 x
38  doTime $ sum1 x
39  putStrLn ""
40  putStrLn "sum2"
41  let x = map (Any . (:[])) list
42  doTime $ sum2 x
43  doTime $ sum2 x
44  doTime $ sum2 x
45  putStrLn ""
46  putStrLn "sum3"
47  let x = map (Any . (:[])) list
48  doTime $ sum3 x
49  doTime $ sum3 x
50  doTime $ sum3 x