Ticket #3245: TypeOfSpeed.hs

File TypeOfSpeed.hs, 947 bytes (added by guest, 5 years ago)

Example code showing performance problem with typeOf

Line 
1{-# LANGUAGE ExistentialQuantification #-}
2
3import Data.Typeable
4import System.CPUTime
5import System.Environment
6
7data Any = forall a. (Typeable a) => Any a
8
9int_type, int_list_type :: TypeRep
10int_type = typeOf (undefined :: Int)
11int_list_type = typeOf (undefined :: [Int])
12
13count1 :: [Any] -> Int
14count1 [] = 0
15count1 (Any x:xs) = count1 xs + (if typeOf x == int_type then 1 else 0)
16
17count2 :: [Any] -> Int
18count2 [] = 0
19count2 (Any x:xs) = count2 xs + (if typeOf x == int_list_type then 1 else 0)
20
21doTime x = do
22  start <- getCPUTime
23  putStr "Result: "
24  print x
25  stop <- getCPUTime
26  putStr "Time(sec): "
27  print (fromIntegral (stop - start) / 1e12)
28
29main = do
30  [len] <- getArgs
31  let list = [1..read len::Int]
32  putStrLn "count1"
33  let x = map Any list
34  doTime $ count1 x
35  doTime $ count1 x
36  doTime $ count1 x
37  putStrLn ""
38  putStrLn "count2"
39  let x = map (Any . (:[])) list
40  doTime $ count2 x
41  doTime $ count2 x
42  doTime $ count2 x