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/use \tr{Read} unnecessarily:]
68 %----------------------------------------------------------------
69 \item[GHC compiles some program constructs slowly:]
70 Deeply-nested list comprehensions seem to be one such; in the past,
71 very large constant tables were bad, too.
73 We'd rather you reported such behaviour as a bug, so that we can try
76 The parts of the compiler that seem most prone to wandering off for a
77 long time are the abstract interpreters (strictness and update
78 analysers). You can turn these off individually with
79 \tr{-fno-strictness}\index{-fno-strictness anti-option} and
80 \tr{-fno-update-analysis}.\index{-fno-update-analysis anti-option}
82 If \tr{-ddump-simpl} produces output after a reasonable time, but
83 \tr{-ddump-stg} doesn't, then it's probably the update analyser
86 If your module has big wads of constant data, GHC may produce a huge
87 basic block that will cause the native-code generator's register
90 If \tr{-ddump-absC} produces output after a reasonable time, but
91 nothing after that---it's probably the native-code generator. Bring
92 on \tr{-fvia-C}\index{-fvia-C option} (not that GCC will be that quick about it, either).
94 %----------------------------------------------------------------
95 \item[Avoid the consistency-check on linking:]
96 Use \tr{-no-link-chk}\index{-no-link-chk}; saves effort. This is probably
97 safe in a I-only-compile-things-one-way setup.
99 %----------------------------------------------------------------
100 \item[Explicit \tr{import} declarations:]
101 Instead of saying \tr{import Foo}, say
102 \tr{import Foo (...stuff I want...)}.
104 Truthfully, the reduction on compilation time will be very small.
105 However, judicious use of \tr{import} declarations can make a
106 program easier to understand, so it may be a good idea anyway.
109 %************************************************************************
111 \subsection[faster]{Faster: producing a program that runs quicker}
112 \index{faster programs, how to produce}
114 %************************************************************************
116 The key tool to use in making your Haskell program run faster are
117 GHC's profiling facilities, described separately in
118 \sectionref{profiling}. There is {\em no substitute} for finding
119 where your program's time/space is {\em really} going, as opposed
120 to where you imagine it is going.
122 Another point to bear in mind: By far the best way to improve a
123 program's performance {\em dramatically} is to use better algorithms.
124 Once profiling has thrown the spotlight on the guilty
125 time-consumer(s), it may be better to re-think your program than to
126 try all the tweaks listed below.
128 Another extremely efficient way to make your program snappy is to use
129 library code that has been Seriously Tuned By Someone Else. You {\em might} be able
130 to write a better quicksort than the one in the HBC library, but it
131 will take you much longer than typing \tr{import QSort}.
132 (Incidentally, it doesn't hurt if the Someone Else is Lennart
135 Please report any overly-slow GHC-compiled programs. The current
136 definition of ``overly-slow'' is ``the HBC-compiled version ran
140 %----------------------------------------------------------------
141 \item[Optimise, using \tr{-O} or \tr{-O2}:] This is the most basic way
142 to make your program go faster. Compilation time will be slower,
143 especially with \tr{-O2}.
145 At present, \tr{-O2} is nearly indistinguishable from \tr{-O}.
147 At version 2.01, \tr{-O} is a dodgy proposition, no matter what.
149 %----------------------------------------------------------------
150 \item[Compile via C and crank up GCC:] Even with \tr{-O}, GHC tries to
151 use a native-code generator, if available. But the native
152 code-generator is designed to be quick, not mind-bogglingly clever.
153 Better to let GCC have a go, as it tries much harder on register
156 So, when we want very fast code, we use: \tr{-O -fvia-C -O2-for-C}.
158 %----------------------------------------------------------------
159 \item[Overloaded functions are not your friend:]
160 Haskell's overloading (using type classes) is elegant, neat, etc.,
161 etc., but it is death to performance if left to linger in an inner
162 loop. How can you squash it?
165 \item[Give explicit type signatures:]
166 Signatures are the basic trick; putting them on exported, top-level
167 functions is good software-engineering practice, anyway.
169 The automatic specialisation of overloaded functions should take care
170 of overloaded local and/or unexported functions.
172 \item[Use \tr{SPECIALIZE} pragmas:]
173 \index{SPECIALIZE pragma}
174 \index{overloading, death to}
175 (UK spelling also accepted.) For key overloaded functions, you can
176 create extra versions (NB: more code space) specialised to particular
177 types. Thus, if you have an overloaded function:
179 hammeredLookup :: Ord key => [(key, value)] -> key -> value
181 If it is heavily used on lists with \tr{Widget} keys, you could
182 specialise it as follows:
184 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
187 To get very fancy, you can also specify a named function to use for
188 the specialised value, by adding \tr{= blah}, as in:
190 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
192 It's {\em Your Responsibility} to make sure that \tr{blah} really
193 behaves as a specialised version of \tr{hammeredLookup}!!!
195 An example in which the \tr{= blah} form will Win Big:
197 toDouble :: Real a => a -> Double
198 toDouble = fromRational . toRational
200 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
201 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
203 The \tr{i2d} function is virtually one machine instruction; the
204 default conversion---via an intermediate \tr{Rational}---is obscenely
205 expensive by comparison.
207 By using the US spelling, your \tr{SPECIALIZE} pragma will work with
208 HBC, too. Note that HBC doesn't support the \tr{= blah} form.
210 A \tr{SPECIALIZE} pragma for a function can be put anywhere its type
211 signature could be put.
213 \item[Use \tr{SPECIALIZE instance} pragmas:]
214 Same idea, except for instance declarations. For example:
216 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
218 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
220 Compatible with HBC, by the way.
222 See also: overlapping instances, in \Sectionref{glasgow-hbc-exts}.
223 They are to \tr{SPECIALIZE instance} pragmas what \tr{= blah}
224 hacks are to \tr{SPECIALIZE} (value) pragmas...
226 \item[``How do I know what's happening with specialisations?'':]
228 The \tr{-fshow-specialisations}\index{-fshow-specialisations option}
229 will show the specialisations that actually take place.
231 The \tr{-fshow-import-specs}\index{-fshow-import-specs option} will
232 show the specialisations that GHC {\em wished} were available, but
233 were not. You can add the relevant pragmas to your code if you wish.
235 You're a bit stuck if the desired specialisation is of a Prelude
236 function. If it's Really Important, you can just snap a copy of the
237 Prelude code, rename it, and then SPECIALIZE that to your heart's
240 \item[``But how do I know where overloading is creeping in?'':]
242 A low-tech way: grep (search) your interface files for overloaded
243 type signatures; e.g.,:
245 % egrep '^[a-z].*::.*=>' *.hi
249 %----------------------------------------------------------------
250 \item[Strict functions are your dear friends:]
251 and, among other things, lazy pattern-matching is your enemy.
253 (If you don't know what a ``strict function'' is, please consult a
254 functional-programming textbook. A sentence or two of
255 explanation here probably would not do much good.)
257 Consider these two code fragments:
259 f (Wibble x y) = ... # strict
261 f arg = let { (Wibble x y) = arg } in ... # lazy
263 The former will result in far better code.
265 A less contrived example shows the use of \tr{cases} instead
266 of \tr{lets} to get stricter code (a good thing):
268 f (Wibble x y) # beautiful but slow
270 (a1, b1, c1) = unpackFoo x
271 (a2, b2, c2) = unpackFoo y
274 f (Wibble x y) # ugly, and proud of it
275 = case (unpackFoo x) of { (a1, b1, c1) ->
276 case (unpackFoo y) of { (a2, b2, c2) ->
281 %----------------------------------------------------------------
282 \item[GHC loves single-constructor data-types:]
284 It's all the better if a function is strict in a single-constructor
285 type (a type with only one data-constructor; for example, tuples are
286 single-constructor types).
288 %----------------------------------------------------------------
289 \item[``How do I find out a function's strictness?'']
291 Don't guess---look it up.
293 Look for your function in the interface file, then for the third field
294 in the pragma; it should say \tr{_S_ <string>}. The \tr{<string>}
295 gives the strictness of the function's arguments. \tr{L} is lazy
296 (bad), \tr{S} and \tr{E} are strict (good), \tr{P} is ``primitive'' (good),
297 \tr{U(...)} is strict and
298 ``unpackable'' (very good), and \tr{A} is absent (very good).
300 For an ``unpackable'' \tr{U(...)} argument, the info inside
301 tells the strictness of its components. So, if the argument is a
302 pair, and it says \tr{U(AU(LSS))}, that means ``the first component of the
303 pair isn't used; the second component is itself unpackable, with three
304 components (lazy in the first, strict in the second \& third).''
306 If the function isn't exported, just compile with the extra flag \tr{-ddump-simpl};
307 next to the signature for any binder, it will print the self-same
308 pragmatic information as would be put in an interface file.
309 (Besides, Core syntax is fun to look at!)
311 %----------------------------------------------------------------
312 \item[Force key functions to be \tr{INLINE}d (esp. monads):]
314 GHC (with \tr{-O}, as always) tries to inline (or ``unfold'')
315 functions/values that are ``small enough,'' thus avoiding the call
316 overhead and possibly exposing other more-wonderful optimisations.
318 You will probably see these unfoldings (in Core syntax) in your
321 Normally, if GHC decides a function is ``too expensive'' to inline, it
322 will not do so, nor will it export that unfolding for other modules to
325 The sledgehammer you can bring to bear is the
326 \tr{INLINE}\index{INLINE pragma} pragma, used thusly:
328 key_function :: Int -> String -> (Bool, Double)
330 #ifdef __GLASGOW_HASKELL__
331 {-# INLINE key_function #-}
334 (You don't need to do the C pre-processor carry-on unless you're going
335 to stick the code through HBC---it doesn't like \tr{INLINE} pragmas.)
337 The major effect of an \tr{INLINE} pragma is to declare a function's
338 ``cost'' to be very low. The normal unfolding machinery will then be
339 very keen to inline it.
341 An \tr{INLINE} pragma for a function can be put anywhere its type
342 signature could be put.
344 \tr{INLINE} pragmas are a particularly good idea for the
345 \tr{then}/\tr{return} (or \tr{bind}/\tr{unit}) functions in a monad.
346 For example, in GHC's own @UniqueSupply@ monad code, we have:
348 #ifdef __GLASGOW_HASKELL__
349 {-# INLINE thenUs #-}
350 {-# INLINE returnUs #-}
354 GHC reserves the right to {\em disallow} any unfolding, even if you
355 explicitly asked for one. That's because a function's body may
356 become {\em unexportable}, because it mentions a non-exported value,
357 to which any importing module would have no access.
359 If you want to see why candidate unfoldings are rejected, use the
360 \tr{-freport-disallowed-unfoldings}
361 \index{-freport-disallowed-unfoldings}
364 %----------------------------------------------------------------
365 \item[Don't let GHC ignore pragmatic information:]
367 Sort-of by definition, GHC is allowed to ignore pragmas in interfaces.
368 Your program should still work, if not as well.
370 Normally, GHC {\em will} ignore an unfolding pragma in an interface if
371 it cannot figure out all the names mentioned in the unfolding. (A
372 very much hairier implementation could make sure This Never Happens,
373 but life is too short to wage constant battle with Haskell's module
376 If you want to prevent such ignorings, give GHC a
377 \tr{-fshow-pragma-name-errs}
378 option.\index{-fshow-pragma-name-errs option}
379 It will then treat any unresolved names in pragmas as {\em
380 errors}, rather than inconveniences.
382 %----------------------------------------------------------------
383 \item[Explicit \tr{export} list:]
384 If you do not have an explicit export list in a module, GHC must
385 assume that everything in that module will be exported. This has
386 various pessimising effect. For example, if a bit of code is actually
387 {\em unused} (perhaps because of unfolding effects), GHC will not be
388 able to throw it away, because it is exported and some other module
389 may be relying on its existence.
391 GHC can be quite a bit more aggressive with pieces of code if it knows
392 they are not exported.
394 %----------------------------------------------------------------
395 \item[Look at the Core syntax!]
396 (The form in which GHC manipulates your code.) Just run your
397 compilation with \tr{-ddump-simpl} (don't forget the \tr{-O}).
399 If profiling has pointed the finger at particular functions, look at
400 their Core code. \tr{lets} are bad, \tr{cases} are good, dictionaries
401 (\tr{d.<Class>.<Unique>}) [or anything overloading-ish] are bad,
402 nested lambdas are bad, explicit data constructors are good, primitive
403 operations (e.g., \tr{eqInt#}) are good, ...
405 %----------------------------------------------------------------
406 \item[Use unboxed types (a GHC extension):]
407 When you are {\em really} desperate for speed, and you want to
408 get right down to the ``raw bits.''
409 Please see \sectionref{glasgow-unboxed} for some information about
412 %----------------------------------------------------------------
413 \item[Use \tr{_ccall_s} (a GHC extension) to plug into fast libraries:]
414 This may take real work, but... There exist piles of
415 massively-tuned library code, and the best thing is not
416 to compete with it, but link with it.
418 \Sectionref{glasgow-ccalls} says a little about how to use C calls.
420 %----------------------------------------------------------------
421 \item[Don't use \tr{Float}s:]
422 We don't provide specialisations of Prelude functions for \tr{Float}
423 (but we do for \tr{Double}). If you end up executing overloaded
424 code, you will lose on performance, perhaps badly.
426 \tr{Floats} (probably 32-bits) are almost always a bad idea, anyway,
427 unless you Really Know What You Are Doing. Use Doubles. There's
428 rarely a speed disadvantage---modern machines will use the same
429 floating-point unit for both. With \tr{Doubles}, you are much less
430 likely to hang yourself with numerical errors.
432 %----------------------------------------------------------------
433 \item[Use a bigger heap!]
434 If your program's GC stats (\tr{-S}\index{-S RTS option} RTS option)
435 indicate that it's doing lots of garbage-collection (say, more than
436 20\% of execution time), more memory might help---with the
437 \tr{-H<size>}\index{-H<size> RTS option} RTS option.
439 %----------------------------------------------------------------
440 \item[Use a smaller heap!]
441 Some programs with a very small heap residency (toy programs, usually)
442 actually benefit from running the heap size way down. The
443 \tr{-H<size>} RTS option, as above.
445 %----------------------------------------------------------------
446 \item[Use a smaller ``allocation area'':]
447 If you can get the garbage-collector's youngest generation to fit
448 entirely in your machine's cache, it may make quite a difference.
449 The effect is {\em very machine dependent}. But, for example,
450 a \tr{+RTS -A128k}\index{-A<size> RTS option} option on one of our
451 DEC Alphas was worth an immediate 5\% performance boost.
454 %************************************************************************
456 \subsection[smaller]{Smaller: producing a program that is smaller}
457 \index{smaller programs, how to produce}
459 %************************************************************************
461 Decrease the ``go-for-it'' threshold for unfolding smallish expressions.
462 Give a \tr{-funfolding-use-threshold0}\index{-funfolding-use-threshold0 option}
463 option for the extreme case. (``Only unfoldings with zero cost should proceed.'')
465 (Note: I have not been too successful at producing code smaller
466 than that which comes out with \tr{-O}. WDP 94/12)
470 Use \tr{strip} on your executables.
472 %************************************************************************
474 \subsection[stingier]{Stingier: producing a program that gobbles less heap space}
475 \index{memory, using less heap}
476 \index{space-leaks, avoiding}
477 \index{heap space, using less}
479 %************************************************************************
481 ``I think I have a space leak...'' Re-run your program with
482 \tr{+RTS -Sstderr},\index{-Sstderr RTS option} and remove all doubt!
483 (You'll see the heap usage get bigger and bigger...) [Hmmm... this
484 might be even easier with the \tr{-F2s}\index{-F2s RTS option} RTS
485 option; so... \tr{./a.out +RTS -Sstderr -F2s}...]
487 Once again, the profiling facilities (\sectionref{profiling}) are the
488 basic tool for demystifying the space behaviour of your program.
490 Strict functions are good to space usage, as they are for time, as
491 discussed in the previous section. Strict functions get right down to
492 business, rather than filling up the heap with closures (the system's
493 notes to itself about how to evaluate something, should it eventually
496 If you have a true blue ``space leak'' (your program keeps gobbling up
497 memory and never ``lets go''), then 7 times out of 10 the problem is
498 related to a {\em CAF} (constant applicative form). Real people call
499 them ``top-level values that aren't functions.'' Thus, for example:
503 ones = [ 1, (1 :: Float), .. ]
505 \tr{x} and \tr{ones} are CAFs; \tr{f} is not.
507 The GHC garbage collectors are not clever about CAFs. The part of the
508 heap reachable from a CAF is never collected. In the case of
509 \tr{ones} in the example above, it's {\em disastrous}. For this
510 reason, the GHC ``simplifier'' tries hard to avoid creating CAFs, but
511 it cannot subvert the will of a determined CAF-writing programmer (as