1 %************************************************************************
3 <sect>Advice on: sooner, faster, smaller, stingier
4 <label id="sooner-faster-quicker">
7 %************************************************************************
9 Please advise us of other ``helpful hints'' that should go here!
11 %************************************************************************
13 <sect1>Sooner: producing a program more quickly
16 <nidx>compiling faster</nidx>
17 <nidx>faster compiling</nidx>
19 %************************************************************************
22 %----------------------------------------------------------------
23 <tag>Don't use @-O@ or (especially) @-O2@:</tag>
24 By using them, you are telling GHC that you are willing to suffer
25 longer compilation times for better-quality code.
27 GHC is surprisingly zippy for normal compilations without @-O@!
29 %----------------------------------------------------------------
30 <tag>Use more memory:</tag>
31 Within reason, more memory for heap space means less garbage
32 collection for GHC, which means less compilation time. If you use
33 the @-Rgc-stats@ option, you'll get a garbage-collector report.
34 (Again, you can use the cheap-and-nasty @-optCrts-Sstderr@ option to
35 send the GC stats straight to standard error.)
37 If it says you're using more than 20\% of total time in garbage
38 collecting, then more memory would help.
40 If the heap size is approaching the maximum (64M by default), and you
41 have lots of memory, try increasing the maximum with the
42 @-M<size>@<nidx>-M<size> option</nidx> option, e.g.: @ghc -c -O
45 Increasing the default allocation area size used by the compiler's RTS
46 might also help: use the @-A<size>@<nidx>-A<size> option</nidx>
49 If GHC persists in being a bad memory citizen, please report it as a
52 %----------------------------------------------------------------
53 <tag>Don't use too much memory!</tag>
54 As soon as GHC plus its ``fellow citizens'' (other processes on your
55 machine) start using more than the <em>real memory</em> on your
56 machine, and the machine starts ``thrashing,'' <em>the party is
57 over</em>. Compile times will be worse than terrible! Use something
58 like the csh-builtin @time@ command to get a report on how many page
59 faults you're getting.
61 If you don't know what virtual memory, thrashing, and page faults are,
62 or you don't know the memory configuration of your machine,
63 <em>don't</em> try to be clever about memory use: you'll just make
64 your life a misery (and for other people, too, probably).
66 %----------------------------------------------------------------
67 <tag>Try to use local disks when linking:</tag>
68 Because Haskell objects and libraries tend to be large, it can take
69 many real seconds to slurp the bits to/from a remote filesystem.
71 It would be quite sensible to <em>compile</em> on a fast machine using
72 remotely-mounted disks; then <em>link</em> on a slow machine that had
73 your disks directly mounted.
75 %----------------------------------------------------------------
76 <tag>Don't derive/use @Read@ unnecessarily:</tag>
79 %----------------------------------------------------------------
80 <tag>GHC compiles some program constructs slowly:</tag>
81 Deeply-nested list comprehensions seem to be one such; in the past,
82 very large constant tables were bad, too.
84 We'd rather you reported such behaviour as a bug, so that we can try
87 The parts of the compiler that seem most prone to wandering off for a
88 long time are the abstract interpreters (strictness and update
89 analysers). You can turn these off individually with
90 @-fno-strictness@<nidx>-fno-strictness anti-option</nidx> and
91 @-fno-update-analysis@.<nidx>-fno-update-analysis anti-option</nidx>
93 To figure out which part of the compiler is badly behaved, the
94 @-dshow-passes@<nidx>-dshow-passes option</nidx> option is your
97 If your module has big wads of constant data, GHC may produce a huge
98 basic block that will cause the native-code generator's register
99 allocator to founder. Bring on @-fvia-C@<nidx>-fvia-C option</nidx>
100 (not that GCC will be that quick about it, either).
102 %----------------------------------------------------------------
103 <tag>Avoid the consistency-check on linking:</tag>
105 Use @-no-link-chk@<nidx>-no-link-chk</nidx>; saves effort. This is
106 probably safe in a I-only-compile-things-one-way setup.
108 %----------------------------------------------------------------
109 <tag>Explicit @import@ declarations:</tag>
111 Instead of saying @import Foo@, say @import Foo (...stuff I want...)@.
113 Truthfully, the reduction on compilation time will be very small.
114 However, judicious use of @import@ declarations can make a
115 program easier to understand, so it may be a good idea anyway.
118 %************************************************************************
120 <sect1>Faster: producing a program that runs quicker
123 <nidx>faster programs, how to produce</nidx>
125 %************************************************************************
127 The key tool to use in making your Haskell program run faster are
128 GHC's profiling facilities, described separately in Section <ref
129 name="Profiling" id="profiling">. There is <em>no substitute</em> for
130 finding where your program's time/space is <em>really</em> going, as
131 opposed to where you imagine it is going.
133 Another point to bear in mind: By far the best way to improve a
134 program's performance <em>dramatically</em> is to use better
135 algorithms. Once profiling has thrown the spotlight on the guilty
136 time-consumer(s), it may be better to re-think your program than to
137 try all the tweaks listed below.
139 Another extremely efficient way to make your program snappy is to use
140 library code that has been Seriously Tuned By Someone Else. You
141 <em>might</em> be able to write a better quicksort than the one in the
142 HBC library, but it will take you much longer than typing @import
143 QSort@. (Incidentally, it doesn't hurt if the Someone Else is Lennart
146 Please report any overly-slow GHC-compiled programs. The current
147 definition of ``overly-slow'' is ``the HBC-compiled version ran
151 %----------------------------------------------------------------
152 <tag>Optimise, using @-O@ or @-O2@:</tag> This is the most basic way
153 to make your program go faster. Compilation time will be slower,
154 especially with @-O2@.
156 At present, @-O2@ is nearly indistinguishable from @-O@.
158 %----------------------------------------------------------------
159 <tag>Compile via C and crank up GCC:</tag> Even with @-O@, GHC tries to
160 use a native-code generator, if available. But the native
161 code-generator is designed to be quick, not mind-bogglingly clever.
162 Better to let GCC have a go, as it tries much harder on register
165 So, when we want very fast code, we use: @-O -fvia-C -O2-for-C@.
167 %----------------------------------------------------------------
168 <tag>Overloaded functions are not your friend:</tag>
169 Haskell's overloading (using type classes) is elegant, neat, etc.,
170 etc., but it is death to performance if left to linger in an inner
171 loop. How can you squash it?
174 <tag>Give explicit type signatures:</tag>
175 Signatures are the basic trick; putting them on exported, top-level
176 functions is good software-engineering practice, anyway. (Tip: using
177 @-fwarn-missing-signatures@<nidx>-fwarn-missing-signatures
178 option</nidx> can help enforce good signature-practice).
180 The automatic specialisation of overloaded functions (with @-O@)
181 should take care of overloaded local and/or unexported functions.
183 <tag>Use @SPECIALIZE@ pragmas:</tag>
184 <nidx>SPECIALIZE pragma</nidx>
185 <nidx>overloading, death to</nidx>
186 (UK spelling also accepted.) For key overloaded functions, you can
187 create extra versions (NB: more code space) specialised to particular
188 types. Thus, if you have an overloaded function:
191 hammeredLookup :: Ord key => [(key, value)] -> key -> value
194 If it is heavily used on lists with @Widget@ keys, you could
195 specialise it as follows:
197 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
200 To get very fancy, you can also specify a named function to use for
201 the specialised value, by adding @= blah@, as in:
203 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
205 It's <em>Your Responsibility</em> to make sure that @blah@ really
206 behaves as a specialised version of @hammeredLookup@!!!
208 [NOTE: this feature isn't implemented in GHC 4.00... ]
210 An example in which the @= blah@ form will Win Big:
212 toDouble :: Real a => a -> Double
213 toDouble = fromRational . toRational
215 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
216 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
218 The @i2d@ function is virtually one machine instruction; the
219 default conversion---via an intermediate @Rational@---is obscenely
220 expensive by comparison.
222 By using the US spelling, your @SPECIALIZE@ pragma will work with
223 HBC, too. Note that HBC doesn't support the @= blah@ form.
225 A @SPECIALIZE@ pragma for a function can be put anywhere its type
226 signature could be put.
228 <tag>Use @SPECIALIZE instance@ pragmas:</tag>
229 Same idea, except for instance declarations. For example:
231 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
233 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
235 Compatible with HBC, by the way.
237 % See also: overlapping instances, in Section <ref name="``HBC-ish''
238 % extensions implemented by GHC" id="glasgow-hbc-exts">. They are to
239 % @SPECIALIZE instance@ pragmas what @= blah@ hacks are to @SPECIALIZE@
242 %ToDo: there's nothing like this at the moment: --SDM
244 % <tag>``How do I know what's happening with specialisations?'':</tag>
246 % The @-fshow-specialisations@<nidx>-fshow-specialisations option</nidx>
247 % will show the specialisations that actually take place.
249 % The @-fshow-import-specs@<nidx>-fshow-import-specs option</nidx> will
250 % show the specialisations that GHC <em>wished</em> 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 <tag>``But how do I know where overloading is creeping in?'':</tag>
260 A low-tech way: grep (search) your interface files for overloaded
261 type signatures; e.g.,:
263 % egrep '^[a-z].*::.*=>' *.hi
267 %----------------------------------------------------------------
268 <tag>Strict functions are your dear friends:</tag>
269 and, among other things, lazy pattern-matching is your enemy.
271 (If you don't know what a ``strict function'' is, please consult a
272 functional-programming textbook. A sentence or two of
273 explanation here probably would not do much good.)
275 Consider these two code fragments:
277 f (Wibble x y) = ... # strict
279 f arg = let { (Wibble x y) = arg } in ... # lazy
281 The former will result in far better code.
283 A less contrived example shows the use of @cases@ instead
284 of @lets@ to get stricter code (a good thing):
286 f (Wibble x y) # beautiful but slow
288 (a1, b1, c1) = unpackFoo x
289 (a2, b2, c2) = unpackFoo y
292 f (Wibble x y) # ugly, and proud of it
293 = case (unpackFoo x) of { (a1, b1, c1) ->
294 case (unpackFoo y) of { (a2, b2, c2) ->
299 %----------------------------------------------------------------
300 <tag>GHC loves single-constructor data-types:</tag>
302 It's all the better if a function is strict in a single-constructor
303 type (a type with only one data-constructor; for example, tuples are
304 single-constructor types).
306 %----------------------------------------------------------------
307 <tag>Newtypes are better than datatypes:</tag>
309 If your datatype has a single constructor with a single field, use a
310 @newtype@ declaration instead of a @data@ declaration. The @newtype@
311 will be optimised away in most cases.
313 %----------------------------------------------------------------
314 <tag>``How do I find out a function's strictness?''</tag>
316 Don't guess---look it up.
318 Look for your function in the interface file, then for the third field
319 in the pragma; it should say @_S_ <string>@. The @<string>@
320 gives the strictness of the function's arguments. @L@ is lazy
321 (bad), @S@ and @E@ are strict (good), @P@ is ``primitive'' (good),
322 @U(...)@ is strict and
323 ``unpackable'' (very good), and @A@ is absent (very good).
325 For an ``unpackable'' @U(...)@ argument, the info inside
326 tells the strictness of its components. So, if the argument is a
327 pair, and it says @U(AU(LSS))@, that means ``the first component of the
328 pair isn't used; the second component is itself unpackable, with three
329 components (lazy in the first, strict in the second \& third).''
331 If the function isn't exported, just compile with the extra flag @-ddump-simpl@;
332 next to the signature for any binder, it will print the self-same
333 pragmatic information as would be put in an interface file.
334 (Besides, Core syntax is fun to look at!)
336 %----------------------------------------------------------------
337 <tag>Force key functions to be @INLINE@d (esp. monads):</tag>
339 GHC (with @-O@, as always) tries to inline (or ``unfold'')
340 functions/values that are ``small enough,'' thus avoiding the call
341 overhead and possibly exposing other more-wonderful optimisations.
343 You will probably see these unfoldings (in Core syntax) in your
346 Normally, if GHC decides a function is ``too expensive'' to inline, it
347 will not do so, nor will it export that unfolding for other modules to
350 The sledgehammer you can bring to bear is the
351 @INLINE@<nidx>INLINE pragma</nidx> pragma, used thusly:
353 key_function :: Int -> String -> (Bool, Double)
355 #ifdef __GLASGOW_HASKELL__
356 {-# INLINE key_function #-}
359 (You don't need to do the C pre-processor carry-on unless you're going
360 to stick the code through HBC---it doesn't like @INLINE@ pragmas.)
362 The major effect of an @INLINE@ pragma is to declare a function's
363 ``cost'' to be very low. The normal unfolding machinery will then be
364 very keen to inline it.
366 An @INLINE@ pragma for a function can be put anywhere its type
367 signature could be put.
369 @INLINE@ pragmas are a particularly good idea for the
370 @then@/@return@ (or @bind@/@unit@) functions in a monad.
371 For example, in GHC's own @UniqueSupply@ monad code, we have:
373 #ifdef __GLASGOW_HASKELL__
374 {-# INLINE thenUs #-}
375 {-# INLINE returnUs #-}
379 Incedentally, there's also a @NOINLINE@<nidx>NOINLINE pragma</nidx>
380 pragma which does the obvious thing.
382 %----------------------------------------------------------------
383 <tag>Explicit @export@ list:</tag>
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 effects. For example, if a bit of code is actually
387 <em>unused</em> (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 <tag>Look at the Core syntax!</tag>
396 (The form in which GHC manipulates your code.) Just run your
397 compilation with @-ddump-simpl@ (don't forget the @-O@).
399 If profiling has pointed the finger at particular functions, look at
400 their Core code. @lets@ are bad, @cases@ are good, dictionaries
401 (@d.<Class>.<Unique>@) [or anything overloading-ish] are bad,
402 nested lambdas are bad, explicit data constructors are good, primitive
403 operations (e.g., @eqInt#@) are good, ...
405 %----------------------------------------------------------------
406 <tag>Use unboxed types (a GHC extension):</tag>
407 When you are <em>really</em> desperate for speed, and you want to get
408 right down to the ``raw bits.'' Please see Section <ref name="Unboxed
409 types" id="glasgow-unboxed"> for some information about using unboxed
412 %----------------------------------------------------------------
413 <tag>Use @_ccall_s@ (a GHC extension) to plug into fast libraries:</tag>
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 Section <ref name="Calling~C directly from Haskell" id="glasgow-ccalls"> says a little about how to use C calls.
420 %----------------------------------------------------------------
421 <tag>Don't use @Float@s:</tag>
422 We don't provide specialisations of Prelude functions for @Float@
423 (but we do for @Double@). If you end up executing overloaded
424 code, you will lose on performance, perhaps badly.
426 @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 @Doubles@, you are much less
430 likely to hang yourself with numerical errors.
432 One time when @Float@ might be a good idea is if you have a
433 <em>lot</em> of them, say a giant array of @Float@s. They take up
434 half the space in the heap compared to @Doubles@. However, this isn't
435 true on a 64-bit machine.
437 %----------------------------------------------------------------
438 <tag>Use a bigger heap!</tag>
440 If your program's GC stats (@-S@<nidx>-S RTS option</nidx> RTS option)
441 indicate that it's doing lots of garbage-collection (say, more than
442 20\% of execution time), more memory might help---with the
443 @-M<size>@<nidx>-M<size> RTS option</nidx> or
444 @-A<size>@<nidx>-A<size> RTS option</nidx> RTS options (see
445 Section <ref name="RTS options to control the garbage-collector"
446 id="rts-options-gc">).
449 %************************************************************************
451 <sect1>Smaller: producing a program that is smaller
454 <nidx>smaller programs, how to produce</nidx>
456 %************************************************************************
458 Decrease the ``go-for-it'' threshold for unfolding smallish
460 @-funfolding-use-threshold0@<nidx>-funfolding-use-threshold0
461 option</nidx> option for the extreme case. (``Only unfoldings with
462 zero cost should proceed.'') Warning: except in certain specialiised
463 cases (like Happy parsers) this is likely to actually
464 <em>increase</em> the size of your program, because unfolding
465 generally enables extra simplifying optimisations to be performed.
469 Use @strip@ on your executables.
471 %************************************************************************
473 <sect1>Stingier: producing a program that gobbles less heap space
474 <label id="stingier">
476 <nidx>memory, using less heap</nidx>
477 <nidx>space-leaks, avoiding</nidx>
478 <nidx>heap space, using less</nidx>
480 %************************************************************************
482 ``I think I have a space leak...'' Re-run your program with
483 @+RTS -Sstderr@,<nidx>-Sstderr RTS option</nidx> and remove all doubt!
484 (You'll see the heap usage get bigger and bigger...) [Hmmm... this
485 might be even easier with the @-F2s@<nidx>-F2s RTS option</nidx> RTS
486 option; so... @./a.out +RTS -Sstderr -F2s@...]
488 Once again, the profiling facilities (Section <ref name="Profiling"
489 id="profiling">) are the basic tool for demystifying the space
490 behaviour of your program.
492 Strict functions are good for space usage, as they are for time, as
493 discussed in the previous section. Strict functions get right down to
494 business, rather than filling up the heap with closures (the system's
495 notes to itself about how to evaluate something, should it eventually