Skip to content
Tutorials Center
My learning

Topics

Lesson 40 of 57 ยท Modules, packages and tooling

Debugging, Profiling and Performance

Find bugs and slow code in Haskell: Debug.Trace, GHC warnings with -Wall, HLint, GHCi breakpoints, profiling, strictness, list fusion and criterion benchmarks.

Haskell's type checker removes many bugs before the program runs, but not all of them. Sooner or later you will have a function that returns the wrong answer, or a program that is correct and far too slow. Because Haskell is pure and lazy, the usual printf debugging and the usual "which line is slow?" intuitions work a little differently.

This lesson goes through the tools in the order you should reach for them: compiler warnings first, then Debug.Trace, GHCi's debugger, HLint, and finally profiling and benchmarking. The Haskell blocks are read-only because GHC is not installed on this site; the runnable stand-ins are JavaScript models of tracing and of list fusion.

Reach for tools in this order

Warnings -Wall finds bugs for free.
Trace Print values from pure code.
GHCi debugger Breakpoints and :step.
Profile Measure before you optimise.
1 / 2

Warnings: the cheapest debugger

GHC can warn about suspicious code. Turn the useful ones on for every project with -Wall, in the ghc-options of your .cabal file (see Cabal, Stack and Packages):

HASKELL
# OPTIONS_GHC -Wall #

module Main (main) where

import Data.List (sort)   -- warning: unused import

describe :: Int -> String
describe 0 = "zero"
describe 1 = "one"        -- warning: patterns not exhaustive

main :: IO ()
main = putStrLn (describe 2)

GHC would report two problems before you ever run this: Data.List (sort) is imported but unused, and describe does not handle every Int, so describe 2 would crash at run time with a non-exhaustive patterns error. The most valuable warnings are:

  • -Wincomplete-patterns (part of -Wall): a case or function that forgets a constructor.
  • -Wunused-imports, -Wunused-matches, -Wunused-top-binds: dead code.
  • -Wname-shadowing: a local name hides another, a classic source of confusion.
  • -Wincomplete-uni-patterns, -Wmissing-signatures, and -Wpartial-fields for risky record fields.

During development -Werror turns warnings into errors, which keeps a codebase clean; many teams enable it only in continuous integration so that a new GHC version does not break users' builds.

Typed holes are another gift. Write _ or _name where you do not know an expression, and the error message lists the expected type and valid fits from your scope.

Debug.Trace: print from pure code

A pure function cannot call putStrLn, because it has no IO type. For debugging, the base library provides Debug.Trace, which prints to standard error as a side effect of evaluating an expression:

HASKELL
import Debug.Trace (trace, traceShow, traceShowId, traceM)

factorial :: Integer -> Integer
factorial n
  | trace ("factorial " ++ show n) False = undefined
  | n <= 1    = 1
  | otherwise = n * factorial (n - 1)

double :: Int -> Int
double x = traceShow ("double called with", x) (x * 2)

total :: Int
total = traceShowId (sum [1, 2, 3])   -- prints 6 and returns 6

The family is small: trace takes a message, traceShow takes any Show value, traceShowId prints and returns its argument, so you can wrap a subexpression without restructuring, and traceM works inside a monadic do block.

Two cautions follow from laziness:

  1. The message appears only when the expression is evaluated. If the value is never demanded, nothing prints. The order of messages follows evaluation order, not the order of lines in the source. (See Lazy Evaluation.)
  2. Never ship it. trace breaks purity on purpose. Delete the calls, or let -Wall and HLint remind you.

The honest model of trace is "print when this thunk is forced". The stand-in below models that behaviour with a small thunk type, so you can see why order can surprise you.

JS Trace prints when a value is forced (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

The trace for b prints first (forcing b starts), and the trace for a appears inside that evaluation, because b needs a. A second use of b prints nothing, since a thunk is evaluated once.

GHCi: breakpoints

GHCi includes a debugger that works on interpreted code (load the module with :l or cabal repl):

TEXT
ghci> :break factorial
ghci> factorial 3
Stopped in Main.factorial, Main.hs:5:3-10
ghci> :show bindings
ghci> :step
ghci> :continue

:break, :step, :continue, :show bindings and :trace let you walk through an evaluation. Laziness means the "step" order is evaluation order again, so it can feel unlike a debugger for a strict language. For many bugs it is quicker to test the function directly in GHCi with the failing input, which is possible precisely because the code is pure. More commands are listed in Installing GHC and using GHCi.

HLint: style and simplification

HLint reads your source and suggests simpler equivalents, such as replacing if x == True with x, or map f (map g xs) with map (f . g) xs.

Terminal
cabal install hlint
hlint src app

Treat its output as advice from a reviewer: it catches redundant brackets, unnecessary do, eta-reducible lambdas and hand-written versions of library functions. Add an .hlint.yaml file to switch off hints your team dislikes.

Measure before optimising

Intuition about performance is often wrong in a lazy language, so measure. A sensible order of attack:

  1. Compile with optimisation. Build with -O2 (Cabal does -O1 by default). Benchmarking an unoptimised build tells you nothing.
  2. Check the algorithm and the data structure. A Map lookup instead of elem on a list, or Data.Text instead of String (see Essential Libraries), usually beats any micro-tuning.
  3. Look at the runtime statistics. Run ./prog +RTS -s (the executable must be linked with -rtsopts). It prints total allocation, maximum memory in use, time spent in garbage collection, and productivity.
  4. Profile. Build with profiling enabled, for example cabal build --enable-profiling --ghc-options="-fprof-auto", then run ./prog +RTS -p. This writes a .prof file that lists cost centres: which functions took the time and allocated the memory. +RTS -hc or -hT produces a heap profile. Profiling changes optimisation a little, so confirm a fix with a normal build.
  5. Fix one thing, measure again.

Strictness and fusion

Two ideas explain most "why is this slow or fat?" questions.

Thunk build-up. A lazy accumulator such as foldl (+) 0, a lazy Map value updated many times, or an IORef modified with modifyIORef holds a growing chain of unevaluated work. The cure is a strict version (foldl', Data.Map.Strict, modifyIORef', bang patterns); see Strictness, Bang Patterns and seq.

Fusion. With -O, GHC rewrites chains of list functions so no intermediate list is built:

HASKELL
sumOfSquares :: Int -> Int
sumOfSquares n = sum (map (^ 2) (filter even [1 .. n]))

Without optimisation this allocates a list for [1 .. n], another for filter, another for map. With optimisation the producers and consumers (enumFromTo, filter, map, sum) are written with the foldr/build rewrite rules, so they fuse into a single loop with no lists at all. Fusion works for standard list functions and for vector pipelines. It stops when a list is used twice, stored in a data structure, or passed to a function GHC does not inline. Use -ddump-simpl to read the optimised core, and -ddump-rule-firings to see which rules fired, if you really need to know.

The stand-in below models the effect: the staged version builds two temporary arrays, the fused version builds none.

JS Staged pipeline versus fused loop (stand-in)

Press Run (or Ctrl + Enter) to see the console output here.

No output.

GHC does this transformation for you; you keep writing the clear pipeline.

Benchmarking with criterion

Timing a program once with a stopwatch is noisy. criterion (and the lighter tasty-bench) runs a function many times, handles warm-up and reports a mean with a confidence interval:

HASKELL
import Criterion.Main

fib :: Int -> Integer
fib n = if n < 2 then toInteger n else fib (n - 1) + fib (n - 2)

main :: IO ()
main = defaultMain
  [ bgroup "fib"
      [ bench "20" $ whnf fib 20
      , bench "25" $ whnf fib 25
      ]
  ]

whnf evaluates the result to weak head normal form for each run, and nf evaluates it fully, which matters for lazy structures (otherwise you time only the creation of an unevaluated thunk). Put benchmarks in a benchmark stanza of the .cabal file, run them with cabal bench, and compare two versions of the same function side by side.

A debugging checklist

  • Does -Wall report anything? Fix it first.
  • Can you reproduce the failure in GHCi with one input? Pure functions make that easy.
  • Can you turn it into a test? Add it to your test suite so it stays fixed.
  • Use traceShowId to look inside an expression, then remove it.
  • For speed: optimise build, better structure, strict accumulators, then profile.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Why does Debug.Trace exist when Haskell functions cannot call putStrLn?

    trace deliberately breaks purity so you can look inside pure code. It should be removed before release.
  2. 2. A trace message never appears. What is the most likely reason?

    Because of lazy evaluation the message only prints when the value is forced.
  3. 3. Which flag turns on a broad set of useful GHC warnings, including incomplete patterns?

    -Wall enables incomplete-patterns, unused imports and many more.
  4. 4. What does fusion do?

    With optimisation GHC rewrites producer and consumer functions into one loop with no temporary lists.
  5. 5. Why use whnf or nf in a criterion benchmark?

    Without forcing the result you would only measure creating a thunk.

Summary

  • Turn on -Wall; fix incomplete patterns, unused imports and shadowing early. Typed holes (_) show expected types.
  • Debug.Trace (trace, traceShow, traceShowId, traceM) prints when an expression is forced; remove it before release.
  • GHCi has :break, :step and :continue, but testing pure functions directly is often faster.
  • HLint suggests simpler code.
  • Measure first: -O2, +RTS -s, profiling builds and heap profiles; then fix one thing at a time.
  • Strict accumulators prevent thunk leaks; fusion removes temporary lists in optimised builds.
  • criterion benchmarks with whnf/nf give reliable timings.

Next: GHC Extensions Worth Knowing.