1 %************************************************************************
3 \section[sooner-faster-quicker]{Advice on: sooner, faster, smaller, stingier}
5 %************************************************************************
7 Please advise us of other ``helpful hints'' that should go here!
9 %************************************************************************
11 \subsection[sooner]{Sooner: producing a program more quickly}
12 \index{compiling faster}
13 \index{faster compiling}
15 %************************************************************************
18 %----------------------------------------------------------------
19 \item[Don't use \tr{-O} or (especially) \tr{-O2}:]
20 By using them, you are telling GHC that you are willing to suffer
21 longer compilation times for better-quality code.
23 GHC is surprisingly zippy for normal compilations without \tr{-O}!
25 %----------------------------------------------------------------
26 \item[Use more memory:]
27 Within reason, more memory for heap space means less garbage
28 collection for GHC, which means less compilation time. If you use
29 the \tr{-Rgc-stats} option, you'll get a garbage-collector report.
30 (Again, you can use the cheap-and-nasty \tr{-optCrts-Sstderr} option to
31 send the GC stats straight to standard error.)
33 If it says you're using more than 20\% of total time in garbage
34 collecting, then more memory would help.
36 You ask for more heap with the \tr{-H<size>}\index{-H<size> option}
37 option; e.g.: \tr{ghc -c -O -H16m Foo.hs}.
39 If GHC persists in being a bad memory citizen, please report it as a
42 %----------------------------------------------------------------
43 \item[Don't use too much memory!]
44 As soon as GHC plus its ``fellow citizens'' (other processes on your machine) start
45 using more than the {\em real memory} on your machine, and the machine
46 starts ``thrashing,'' {\em the party is over}. Compile times will be
47 worse than terrible! Use something like the csh-builtin \tr{time}
48 command to get a report on how many page faults you're getting.
50 If you don't know what virtual memory, thrashing, and page faults are,
51 or you don't know the memory configuration of your machine, {\em
52 don't} try to be clever about memory use: you'll just make your life a
53 misery (and for other people, too, probably).
55 %----------------------------------------------------------------
56 \item[Try to use local disks when linking:]
57 Because Haskell objects and libraries tend to be large, it can take
58 many real seconds to slurp the bits to/from an NFS filesystem (say).
60 It would be quite sensible to {\em compile} on a fast machine using
61 remotely-mounted disks; then {\em link} on a slow machine that had
62 your disks directly mounted.
64 %----------------------------------------------------------------
65 \item[Don't derive \tr{read} for \tr{Text} unnecessarily:]
66 When doing \tr{deriving Text},
67 use \tr{-fomit-derived-read}\index{-fomit-derived-read option}
68 to derive only the \tr{showsPrec} method. Quicker, smaller code.
70 %----------------------------------------------------------------
71 \item[Don't re-export instance declarations:]
73 (Note: This recommendation totally violates the Haskell language
76 The Haskell module system dictates that instance declarations are
77 exported and re-exported into interface files with considerable gusto.
78 In a large system, especially one with mutually-recursive modules,
79 this tendency makes your interface files bigger (bad) and decreases
80 the chances that changes will be propagated incorrectly (bad).
82 If you wish, you may use a language-violating option,
83 \tr{-fomit-reexported-instances},
84 \index{-fomit-reexported-instances option}
85 to get just the effect you might expect. It can't help but
88 %----------------------------------------------------------------
89 \item[GHC compiles some program constructs slowly:]
90 Deeply-nested list comprehensions seem to be one such; in the past,
91 very large constant tables were bad, too.
93 We'd rather you reported such behaviour as a bug, so that we can try
96 The parts of the compiler that seem most prone to wandering off for a
97 long time are the abstract interpreters (strictness and update
98 analysers). You can turn these off individually with
99 \tr{-fno-strictness}\index{-fno-strictness anti-option} and
100 \tr{-fno-update-analysis}.\index{-fno-update-analysis anti-option}
102 If \tr{-ddump-simpl} produces output after a reasonable time, but
103 \tr{-ddump-stg} doesn't, then it's probably the update analyser
106 If your module has big wads of constant data, GHC may produce a huge
107 basic block that will cause the native-code generator's register
108 allocator to founder.
110 If \tr{-ddump-absC} produces output after a reasonable time, but
111 nothing after that---it's probably the native-code generator. Bring
112 on \tr{-fvia-C}\index{-fvia-C option} (not that GCC will be that quick about it, either).
114 %----------------------------------------------------------------
115 \item[Avoid the consistency-check on linking:]
116 Use \tr{-no-link-chk}\index{-no-link-chk}; saves effort. This is probably
117 safe in a I-only-compile-things-one-way setup.
119 %----------------------------------------------------------------
120 \item[Explicit \tr{import} declarations:]
121 Instead of saying \tr{import Foo}, say
122 \tr{import Foo (...stuff I want...)}.
124 Truthfully, the reduction on compilation time will be very small.
125 However, judicious use of \tr{import} declarations can make a
126 program easier to understand, so it may be a good idea anyway.
129 %************************************************************************
131 \subsection[faster]{Faster: producing a program that runs quicker}
132 \index{faster programs, how to produce}
134 %************************************************************************
136 The key tool to use in making your Haskell program run faster are
137 GHC's profiling facilities, described separately in
138 \sectionref{profiling}. There is {\em no substitute} for finding
139 where your program's time/space is {\em really} going, as opposed
140 to where you imagine it is going.
142 Another point to bear in mind: By far the best way to improve a
143 program's performance {\em dramatically} is to use better algorithms.
144 Once profiling has thrown the spotlight on the guilty
145 time-consumer(s), it may be better to re-think your program than to
146 try all the tweaks listed below.
148 Another extremely efficient way to make your program snappy is to use
149 library code that has been Seriously Tuned By Someone Else. You {\em might} be able
150 to write a better quicksort than the one in the HBC library, but it
151 will take you much longer than typing \tr{import QSort}.
152 (Incidentally, it doesn't hurt if the Someone Else is Lennart
155 Please report any overly-slow GHC-compiled programs. The current
156 definition of ``overly-slow'' is ``the HBC-compiled version ran
160 %----------------------------------------------------------------
161 \item[Optimise, using \tr{-O} or \tr{-O2}:] This is the most basic way
162 to make your program go faster. Compilation time will be slower,
163 especially with \tr{-O2}.
165 At version~0.26, \tr{-O2} is nearly indistinguishable from \tr{-O}.
167 %----------------------------------------------------------------
168 \item[Compile via C and crank up GCC:] Even with \tr{-O}, GHC tries to
169 use a native-code generator, if available. But the native
170 code-generator is designed to be quick, not mind-bogglingly clever.
171 Better to let GCC have a go, as it tries much harder on register
174 So, when we want very fast code, we use: \tr{-O -fvia-C -O2-for-C}.
176 %----------------------------------------------------------------
177 \item[Overloaded functions are not your friend:]
178 Haskell's overloading (using type classes) is elegant, neat, etc.,
179 etc., but it is death to performance if left to linger in an inner
180 loop. How can you squash it?
183 \item[Give explicit type signatures:]
184 Signatures are the basic trick; putting them on exported, top-level
185 functions is good software-engineering practice, anyway.
187 The automatic specialisation of overloaded functions should take care
188 of overloaded local and/or unexported functions.
190 \item[Use \tr{SPECIALIZE} pragmas:]
191 \index{SPECIALIZE pragma}
192 \index{overloading, death to}
193 (UK spelling also accepted.) For key overloaded functions, you can
194 create extra versions (NB: more code space) specialised to particular
195 types. Thus, if you have an overloaded function:
197 hammeredLookup :: Ord key => [(key, value)] -> key -> value
199 If it is heavily used on lists with \tr{Widget} keys, you could
200 specialise it as follows:
202 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
205 To get very fancy, you can also specify a named function to use for
206 the specialised value, by adding \tr{= blah}, as in:
208 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
210 It's {\em Your Responsibility} to make sure that \tr{blah} really
211 behaves as a specialised version of \tr{hammeredLookup}!!!
213 An example in which the \tr{= blah} form will Win Big:
215 toDouble :: Real a => a -> Double
216 toDouble = fromRational . toRational
218 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
219 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
221 The \tr{i2d} function is virtually one machine instruction; the
222 default conversion---via an intermediate \tr{Rational}---is obscenely
223 expensive by comparison.
225 By using the US spelling, your \tr{SPECIALIZE} pragma will work with
226 HBC, too. Note that HBC doesn't support the \tr{= blah} form.
228 A \tr{SPECIALIZE} pragma for a function can be put anywhere its type
229 signature could be put.
231 \item[Use \tr{SPECIALIZE instance} pragmas:]
232 Same idea, except for instance declarations. For example:
234 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
236 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
238 Compatible with HBC, by the way.
240 See also: overlapping instances, in \Sectionref{glasgow-hbc-exts}.
241 They are to \tr{SPECIALIZE instance} pragmas what \tr{= blah}
242 hacks are to \tr{SPECIALIZE} (value) pragmas...
244 \item[``How do I know what's happening with specialisations?'':]
246 The \tr{-fshow-specialisations}\index{-fshow-specialisations option}
247 will show the specialisations that actually take place.
249 The \tr{-fshow-import-specs}\index{-fshow-import-specs option} will
250 show the specialisations that GHC {\em wished} were available, but
251 were not. You can add the relevant pragmas to your code if you wish.
253 You're a bit stuck if the desired specialisation is of a Prelude
254 function. If it's Really Important, you can just snap a copy of the
255 Prelude code, rename it, and then SPECIALIZE that to your heart's
258 \item[``But how do I know where overloading is creeping in?'':]
260 A low-tech way: grep (search) your interface files for overloaded
261 type signatures; e.g.,:
263 % egrep '^[a-z].*::.*=>' *.hi
266 Note: explicit export lists sometimes ``mask'' overloaded top-level
267 functions; i.e., you won't see anything about them in the interface
268 file. I sometimes remove my export list temporarily, just to see what
272 %----------------------------------------------------------------
273 \item[Strict functions are your dear friends:]
274 and, among other things, lazy pattern-matching is your enemy.
276 (If you don't know what a ``strict function'' is, please consult a
277 functional-programming textbook. A sentence or two of
278 explanation here probably would not do much good.)
280 Consider these two code fragments:
282 f (Wibble x y) = ... # strict
284 f arg = let { (Wibble x y) = arg } in ... # lazy
286 The former will result in far better code.
288 A less contrived example shows the use of \tr{cases} instead
289 of \tr{lets} to get stricter code (a good thing):
291 f (Wibble x y) # beautiful but slow
293 (a1, b1, c1) = unpackFoo x
294 (a2, b2, c2) = unpackFoo y
297 f (Wibble x y) # ugly, and proud of it
298 = case (unpackFoo x) of { (a1, b1, c1) ->
299 case (unpackFoo y) of { (a2, b2, c2) ->
304 %----------------------------------------------------------------
305 \item[GHC loves single-constructor data-types:]
307 It's all the better if a function is strict in a single-constructor
308 type (a type with only one data-constructor; for example, tuples are
309 single-constructor types).
311 %----------------------------------------------------------------
312 \item[``How do I find out a function's strictness?'']
314 Don't guess---look it up.
316 Look for your function in the interface file, then for the third field
317 in the pragma; it should say \tr{_S_ <string>}. The \tr{<string>}
318 gives the strictness of the function's arguments. \tr{L} is lazy
319 (bad), \tr{S} and \tr{E} are strict (good), \tr{P} is ``primitive'' (good),
320 \tr{U(...)} is strict and
321 ``unpackable'' (very good), and \tr{A} is absent (very good).
323 For an ``unpackable'' \tr{U(...)} argument, the info inside
324 tells the strictness of its components. So, if the argument is a
325 pair, and it says \tr{U(AU(LSS))}, that means ``the first component of the
326 pair isn't used; the second component is itself unpackable, with three
327 components (lazy in the first, strict in the second \& third).''
329 If the function isn't exported, just compile with the extra flag \tr{-ddump-simpl};
330 next to the signature for any binder, it will print the self-same
331 pragmatic information as would be put in an interface file.
332 (Besides, Core syntax is fun to look at!)
334 %----------------------------------------------------------------
335 \item[Force key functions to be \tr{INLINE}d (esp. monads):]
337 GHC (with \tr{-O}, as always) tries to inline (or ``unfold'')
338 functions/values that are ``small enough,'' thus avoiding the call
339 overhead and possibly exposing other more-wonderful optimisations.
341 You will probably see these unfoldings (in Core syntax) in your
344 Normally, if GHC decides a function is ``too expensive'' to inline, it
345 will not do so, nor will it export that unfolding for other modules to
348 The sledgehammer you can bring to bear is the
349 \tr{INLINE}\index{INLINE pragma} pragma, used thusly:
351 key_function :: Int -> String -> (Bool, Double)
353 #ifdef __GLASGOW_HASKELL__
354 {-# INLINE key_function #-}
357 (You don't need to do the C pre-processor carry-on unless you're going
358 to stick the code through HBC---it doesn't like \tr{INLINE} pragmas.)
360 The major effect of an \tr{INLINE} pragma is to declare a function's
361 ``cost'' to be very low. The normal unfolding machinery will then be
362 very keen to inline it.
364 An \tr{INLINE} pragma for a function can be put anywhere its type
365 signature could be put.
367 \tr{INLINE} pragmas are a particularly good idea for the
368 \tr{then}/\tr{return} (or \tr{bind}/\tr{unit}) functions in a monad.
369 For example, in GHC's own @UniqueSupply@ monad code, we have:
371 #ifdef __GLASGOW_HASKELL__
372 {-# INLINE thenUs #-}
373 {-# INLINE returnUs #-}
377 GHC reserves the right to {\em disallow} any unfolding, even if you
378 explicitly asked for one. That's because a function's body may
379 become {\em unexportable}, because it mentions a non-exported value,
380 to which any importing module would have no access.
382 If you want to see why candidate unfoldings are rejected, use the
383 \tr{-freport-disallowed-unfoldings}
384 \index{-freport-disallowed-unfoldings}
387 %----------------------------------------------------------------
388 \item[Don't let GHC ignore pragmatic information:]
390 Sort-of by definition, GHC is allowed to ignore pragmas in interfaces.
391 Your program should still work, if not as well.
393 Normally, GHC {\em will} ignore an unfolding pragma in an interface if
394 it cannot figure out all the names mentioned in the unfolding. (A
395 very much hairier implementation could make sure This Never Happens,
396 but life is too short to wage constant battle with Haskell's module
399 If you want to prevent such ignorings, give GHC a
400 \tr{-fshow-pragma-name-errs}
401 option.\index{-fshow-pragma-name-errs option}
402 It will then treat any unresolved names in pragmas as {\em
403 errors}, rather than inconveniences.
405 %----------------------------------------------------------------
406 \item[Explicit \tr{export} list:]
407 If you do not have an explicit export list in a module, GHC must
408 assume that everything in that module will be exported. This has
409 various pessimising effect. For example, if a bit of code is actually
410 {\em unused} (perhaps because of unfolding effects), GHC will not be
411 able to throw it away, because it is exported and some other module
412 may be relying on its existence.
414 GHC can be quite a bit more aggressive with pieces of code if it knows
415 they are not exported.
417 %----------------------------------------------------------------
418 \item[Look at the Core syntax!]
419 (The form in which GHC manipulates your code.) Just run your
420 compilation with \tr{-ddump-simpl} (don't forget the \tr{-O}).
422 If profiling has pointed the finger at particular functions, look at
423 their Core code. \tr{lets} are bad, \tr{cases} are good, dictionaries
424 (\tr{d.<Class>.<Unique>}) [or anything overloading-ish] are bad,
425 nested lambdas are bad, explicit data constructors are good, primitive
426 operations (e.g., \tr{eqInt#}) are good, ...
428 %----------------------------------------------------------------
429 \item[Use unboxed types (a GHC extension):]
430 When you are {\em really} desperate for speed, and you want to
431 get right down to the ``raw bits.''
432 Please see \sectionref{glasgow-unboxed} for some information about
435 %----------------------------------------------------------------
436 \item[Use \tr{_ccall_s} (a GHC extension) to plug into fast libraries:]
437 This may take real work, but... There exist piles of
438 massively-tuned library code, and the best thing is not
439 to compete with it, but link with it.
441 \Sectionref{glasgow-ccalls} says a little about how to use C calls.
443 %----------------------------------------------------------------
444 \item[Don't use \tr{Float}s:]
445 We don't provide specialisations of Prelude functions for \tr{Float}
446 (but we do for \tr{Double}). If you end up executing overloaded
447 code, you will lose on performance, perhaps badly.
449 \tr{Floats} (probably 32-bits) are almost always a bad idea, anyway,
450 unless you Really Know What You Are Doing. Use Doubles. There's
451 rarely a speed disadvantage---modern machines will use the same
452 floating-point unit for both. With \tr{Doubles}, you are much less
453 likely to hang yourself with numerical errors.
455 %----------------------------------------------------------------
456 \item[Use a bigger heap!]
457 If your program's GC stats (\tr{-S}\index{-S RTS option} RTS option)
458 indicate that it's doing lots of garbage-collection (say, more than
459 20\% of execution time), more memory might help---with the
460 \tr{-H<size>}\index{-H<size> RTS option} RTS option.
462 %----------------------------------------------------------------
463 \item[Use a smaller heap!]
464 Some programs with a very small heap residency (toy programs, usually)
465 actually benefit from running the heap size way down. The
466 \tr{-H<size>} RTS option, as above.
468 %----------------------------------------------------------------
469 \item[Use a smaller ``allocation area'':]
470 If you can get the garbage-collector's youngest generation to fit
471 entirely in your machine's cache, it may make quite a difference.
472 The effect is {\em very machine dependent}. But, for example,
473 a \tr{+RTS -A128k}\index{-A<size> RTS option} option on one of our
474 DEC Alphas was worth an immediate 5\% performance boost.
477 %************************************************************************
479 \subsection[smaller]{Smaller: producing a program that is smaller}
480 \index{smaller programs, how to produce}
482 %************************************************************************
484 Decrease the ``go-for-it'' threshold for unfolding smallish expressions.
485 Give a \tr{-funfolding-use-threshold0}\index{-funfolding-use-threshold0 option}
486 option for the extreme case. (``Only unfoldings with zero cost should proceed.'')
488 (Note: I have not been too successful at producing code smaller
489 than that which comes out with \tr{-O}. WDP 94/12)
491 Use \tr{-fomit-derived-read} if you are using a lot of derived
492 instances of \tr{Text} (and don't need the read methods).
494 Use \tr{strip} on your executables.
496 %************************************************************************
498 \subsection[stingier]{Stingier: producing a program that gobbles less heap space}
499 \index{memory, using less heap}
500 \index{space-leaks, avoiding}
501 \index{heap space, using less}
503 %************************************************************************
505 ``I think I have a space leak...'' Re-run your program with
506 \tr{+RTS -Sstderr},\index{-Sstderr RTS option} and remove all doubt!
507 (You'll see the heap usage get bigger and bigger...) [Hmmm... this
508 might be even easier with the \tr{-F2s}\index{-F2s RTS option} RTS
509 option; so... \tr{./a.out +RTS -Sstderr -F2s}...]
511 Once again, the profiling facilities (\sectionref{profiling}) are the
512 basic tool for demystifying the space behaviour of your program.
514 Strict functions are good to space usage, as they are for time, as
515 discussed in the previous section. Strict functions get right down to
516 business, rather than filling up the heap with closures (the system's
517 notes to itself about how to evaluate something, should it eventually
520 If you have a true blue ``space leak'' (your program keeps gobbling up
521 memory and never ``lets go''), then 7 times out of 10 the problem is
522 related to a {\em CAF} (constant applicative form). Real people call
523 them ``top-level values that aren't functions.'' Thus, for example:
527 ones = [ 1, (1 :: Float), .. ]
529 \tr{x} and \tr{ones} are CAFs; \tr{f} is not.
531 The GHC garbage collectors are not clever about CAFs. The part of the
532 heap reachable from a CAF is never collected. In the case of
533 \tr{ones} in the example above, it's {\em disastrous}. For this
534 reason, the GHC ``simplifier'' tries hard to avoid creating CAFs, but
535 it cannot subvert the will of a determined CAF-writing programmer (as