Haskell Profiling Concepts
Profiling is measuring where a program spends its work. A profiler counts work per cost centre so the expensive part can be found first.
Counts show how much each stage handles
The first count covers the whole input. The second count covers only the even numbers kept by the filter.
main :: IO ()
main = do
let xs = [1..20]
print (length xs)
print (length (filter even xs))Separate functions give separate countable results
Each stage is its own function. Each function prints its own result, so the stages can be compared.
stageA :: [Int] -> Int
stageA xs = sum (map (*2) xs)
stageB :: [Int] -> Int
stageB xs = sum (filter even xs)
main :: IO ()
main = do
print (stageA [1..10])
print (stageB [1..10])One fold counts work and total together
The fold carries a pair. The pair holds the count of items seen and the running total.
main :: IO ()
main = do
let (n, total) = foldl (\(c, s) x -> (c + 1, s + x)) (0, 0) [1..50]
print n
print totalExample
main :: IO ()
main = do
let input = [1..30]
let doubled = map (*2) input
let kept = filter (>20) doubled
print (length doubled)
print (length kept)
print (sum kept)Key points
- Profiling: measuring where a program spends its work.
- Cost centre: a named part of a program whose work the profiler counts separately.
- Compiler flag: an option passed to GHC that turns profiling support on.
- Use separate functions for separate stages so each stage can be counted on its own.
- Counted output: a count or result printed by the program itself, which the harness can check.
In this example, the program doubles the numbers from 1 to 30, keeps only the doubled values above 20, then prints the size of each stage and the sum of the kept values.
Note
this lesson never claims profiler output, because the harness runs plain compiled programs with no profiling flags.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Haskell Playground
Exercise
What is a cost centre in profiling?