🎓 A1Learner
🔍
0 of 50 lessons completed

Haskell Profiling Notes

Profiling notes are the written plan for finding where a program spends its effort. They name compiler flags and strictness tools instead of guessing from a single run.

A bang pattern forces a value at once

The bang pattern forces the addition at once. The printed value is the counted proof.

{-# LANGUAGE BangPatterns #-}
main :: IO ()
main = do
  let !v = 2 + 3
  print v

A strict fold avoids a lazy tower

The strict fold adds 100 numbers without building a tower of additions. The count and the sum are printed.

import Data.List (foldl')
main :: IO ()
main = do
  let xs = [1..100]
  print (length xs)
  print (foldl' (+) 0 xs)

seq forces a total before printing

seq forces the total before it is printed. The printed total is 1275.

main :: IO ()
main = do
  let total = sum [1..50]
  print (total `seq` total)

Example

import Data.List (foldl')
main :: IO ()
main = do
  let words = ["red", "blue", "green"]
  print (length words)
  print (foldl' (+) 0 (map length words))

Key points

  • Profiling flag: a compiler option that asks GHC to record cost information, such as -prof.
  • Cost centre: a labelled part of a program whose cost the profiler can report.
  • Use -prof with -fprof-auto to let GHC label top-level functions for profiling.
  • Use strictness tools such as foldl' and bang patterns to remove lazy towers before profiling.
  • Use counted outputs to check a strict version, since a plain run prints no timing or profiler report.

In this example, the program holds three words. It prints the word count, then the strict sum of their lengths, which is 12, so the strict version is checked by counted output.

Note

A plain compiled run prints counts and results, not a profiler report.

Try it Yourself

Edit the code, then press Run.

Running is simulated · Haskell Playground

Exercise

Which compiler flag asks GHC to record cost information for profiling?