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