Yann Rolland
Yann Rolland

Reputation: 93

Haskell/GHC memory usage

I'm playing around with Haskell and writing files. Here is a little piece of code that for every "blue" in [0..255] creates an image in PPM with "red" and "green" in [0..255]. It produces within a folder all images.

This little program makes my computer crash buy using more than 5 gB of memory and I don't know why. What I asked him to do seems pretty simple for me and the total space taken by generated images is - 200 mB ... and don't understand why memory explodes.

Here is the code :

import System.Directory
import Data.Colour.SRGB
import Data.List.Split

gridColours         = [[RGB 255 0 0, RGB 0 255 0], [RGB 0 0 255, RGB 0 0 0]]
gridColours2 b      = chunksOf 256 [RGB r g b| r <- [0..255], g <- [0..255]]

dimensions l        = (length . head $ l, length l)
coupleToList (a,b)  = [a,b]
genDataLines list   = unwords . (map showColour) . concat $ list
genDims list        = unwords . (map show) . coupleToList . dimensions $ list
writePPM list path  = writeFile path $ unwords $ ["P3", genDims list, "255", genDataLines list]
showColour c        = unwords . (map show) $ [channelRed c, channelGreen c, channelBlue c]

main = do
    createDirectoryIfMissing True "/tmp/PPM-out/"
    mapM_ (\x -> writePPM (gridColours2 x) ("/tmp/PPM-out/image"++(show x)++".ppm")) [0..255]

A perfect answer would explain me what I did wrong and give me advices about how to solve this problem of memory to my system from crashing.

Thank you.

Upvotes: 2

Views: 880

Answers (1)

Daniel Wagner
Daniel Wagner

Reputation: 152682

Compile instead of running from within ghci. On my machine this took virt usage from 5GB to 140MB; res never went above about 15MB for the compiled version. In general (with a very few exceptions), the performance characteristics of ghci are much, much worse than that of a compiled program.

Upvotes: 6

Related Questions