[project @ 1998-12-02 13:17:09 by simonm]
[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 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&lt;size&gt; option</nidx> option, e.g.: @ghc -c -O
43 -M16m Foo.hs@.
44
45 Increasing the default allocation area size used by the compiler's RTS
46 might also help: use the @-A<size>@<nidx>-A&lt;size&gt; option</nidx>
47 option.
48
49 If GHC persists in being a bad memory citizen, please report it as a
50 bug.
51
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.
60
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).
65
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.
70
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.
74
75 %----------------------------------------------------------------
76 <tag>Don't derive/use @Read@ unnecessarily:</tag>
77 It's ugly and slow.
78
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.
83
84 We'd rather you reported such behaviour as a bug, so that we can try
85 to correct it.
86
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>
92
93 To figure out which part of the compiler is badly behaved, the
94 @-dshow-passes@<nidx>-dshow-passes option</nidx> option is your
95 friend.
96
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).
101
102 %----------------------------------------------------------------
103 <tag>Avoid the consistency-check on linking:</tag>
104
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.
107
108 %----------------------------------------------------------------
109 <tag>Explicit @import@ declarations:</tag>
110
111 Instead of saying @import Foo@, say @import Foo (...stuff I want...)@.
112
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.
116 </descrip>
117
118 %************************************************************************
119 %*                                                                      *
120 <sect1>Faster: producing a program that runs quicker
121 <label id="faster">
122 <p>
123 <nidx>faster programs, how to produce</nidx>
124 %*                                                                      *
125 %************************************************************************
126
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.
132
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.
138
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
144 Augustsson.)
145
146 Please report any overly-slow GHC-compiled programs.  The current
147 definition of ``overly-slow'' is ``the HBC-compiled version ran
148 faster''...
149
150 <descrip>
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@.
155
156 At present, @-O2@ is nearly indistinguishable from @-O@.
157
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
163 allocation, etc.
164
165 So, when we want very fast code, we use: @-O -fvia-C -O2-for-C@.
166
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?
172
173 <descrip>
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).
179
180 The automatic specialisation of overloaded functions (with @-O@)
181 should take care of overloaded local and/or unexported functions.
182
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:
189
190 <tscreen><verb>
191 hammeredLookup :: Ord key => [(key, value)] -> key -> value
192 </verb></tscreen>
193
194 If it is heavily used on lists with @Widget@ keys, you could
195 specialise it as follows:
196 <tscreen><verb>
197 {-# SPECIALIZE hammeredLookup :: [(Widget, value)] -> Widget -> value #-}
198 </verb></tscreen>
199
200 To get very fancy, you can also specify a named function to use for
201 the specialised value, by adding @= blah@, as in:
202 <tscreen><verb>
203 {-# SPECIALIZE hammeredLookup :: ...as before... = blah #-}
204 </verb></tscreen>
205 It's <em>Your Responsibility</em> to make sure that @blah@ really
206 behaves as a specialised version of @hammeredLookup@!!!
207
208 [NOTE: this feature isn't implemented in GHC 4.00... ]
209
210 An example in which the @= blah@ form will Win Big:
211 <tscreen><verb>
212 toDouble :: Real a => a -> Double
213 toDouble = fromRational . toRational
214
215 {-# SPECIALIZE toDouble :: Int -> Double = i2d #-}
216 i2d (I# i) = D# (int2Double# i) -- uses Glasgow prim-op directly
217 </verb></tscreen>
218 The @i2d@ function is virtually one machine instruction; the
219 default conversion---via an intermediate @Rational@---is obscenely
220 expensive by comparison.
221
222 By using the US spelling, your @SPECIALIZE@ pragma will work with
223 HBC, too.  Note that HBC doesn't support the @= blah@ form.
224
225 A @SPECIALIZE@ pragma for a function can be put anywhere its type
226 signature could be put.
227
228 <tag>Use @SPECIALIZE instance@ pragmas:</tag>
229 Same idea, except for instance declarations.  For example:
230 <tscreen><verb>
231 instance (Eq a) => Eq (Foo a) where { ... usual stuff ... }
232
233 {-# SPECIALIZE instance Eq (Foo [(Int, Bar)] #-}
234 </verb></tscreen>
235 Compatible with HBC, by the way.
236
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@
240 % (value) pragmas...
241
242 %ToDo: there's nothing like this at the moment: --SDM
243
244 % <tag>``How do I know what's happening with specialisations?'':</tag>
245
246 % The @-fshow-specialisations@<nidx>-fshow-specialisations option</nidx>
247 % will show the specialisations that actually take place.
248
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.
252
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
256 % content.
257
258 <tag>``But how do I know where overloading is creeping in?'':</tag>
259
260 A low-tech way: grep (search) your interface files for overloaded
261 type signatures; e.g.,:
262 <tscreen><verb>
263 % egrep '^[a-z].*::.*=>' *.hi
264 </verb></tscreen>
265 </descrip>
266
267 %----------------------------------------------------------------
268 <tag>Strict functions are your dear friends:</tag>
269 and, among other things, lazy pattern-matching is your enemy.
270
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.)
274
275 Consider these two code fragments:
276 <tscreen><verb>
277 f (Wibble x y) =  ... # strict
278
279 f arg = let { (Wibble x y) = arg } in ... # lazy
280 </verb></tscreen>
281 The former will result in far better code.
282
283 A less contrived example shows the use of @cases@ instead
284 of @lets@ to get stricter code (a good thing):
285 <tscreen><verb>
286 f (Wibble x y)  # beautiful but slow
287   = let
288         (a1, b1, c1) = unpackFoo x
289         (a2, b2, c2) = unpackFoo y
290     in ...
291
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) ->
295     ...
296     }}
297 </verb></tscreen>
298
299 %----------------------------------------------------------------
300 <tag>GHC loves single-constructor data-types:</tag>
301
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).
305
306 %----------------------------------------------------------------
307 <tag>Newtypes are better than datatypes:</tag>
308
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.
312
313 %----------------------------------------------------------------
314 <tag>``How do I find out a function's strictness?''</tag>
315
316 Don't guess---look it up.
317
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).
324
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).''
330
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!)
335
336 %----------------------------------------------------------------
337 <tag>Force key functions to be @INLINE@d (esp. monads):</tag>
338
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.
342
343 You will probably see these unfoldings (in Core syntax) in your
344 interface files.
345
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
348 use.
349
350 The sledgehammer you can bring to bear is the
351 @INLINE@<nidx>INLINE pragma</nidx> pragma, used thusly:
352 <tscreen><verb>
353 key_function :: Int -> String -> (Bool, Double) 
354
355 #ifdef __GLASGOW_HASKELL__
356 {-# INLINE key_function #-}
357 #endif
358 </verb></tscreen>
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.)
361
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.
365
366 An @INLINE@ pragma for a function can be put anywhere its type
367 signature could be put.
368
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:
372 <tscreen><verb>
373 #ifdef __GLASGOW_HASKELL__
374 {-# INLINE thenUs #-}
375 {-# INLINE returnUs #-}
376 #endif
377 </verb></tscreen>
378
379 Incedentally, there's also a @NOINLINE@<nidx>NOINLINE pragma</nidx>
380 pragma which does the obvious thing.
381
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.
390
391 GHC can be quite a bit more aggressive with pieces of code if it knows
392 they are not exported.
393
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@).
398
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, ...
404
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
410 types.
411
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.
417
418 Section <ref name="Calling~C directly from Haskell" id="glasgow-ccalls"> says a little about how to use C calls.
419
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.
425
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.
431
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.
436
437 %----------------------------------------------------------------
438 <tag>Use a bigger heap!</tag>
439
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&lt;size&gt; RTS option</nidx> or
444 @-A<size>@<nidx>-A&lt;size&gt; RTS option</nidx> RTS options (see
445 Section <ref name="RTS options to control the garbage-collector"
446 id="rts-options-gc">).
447 </descrip>
448
449 %************************************************************************
450 %*                                                                      *
451 <sect1>Smaller: producing a program that is smaller
452 <label id="smaller">
453 <p>
454 <nidx>smaller programs, how to produce</nidx>
455 %*                                                                      *
456 %************************************************************************
457
458 Decrease the ``go-for-it'' threshold for unfolding smallish
459 expressions.  Give a
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.
466
467 Avoid @Read@.
468
469 Use @strip@ on your executables.
470
471 %************************************************************************
472 %*                                                                      *
473 <sect1>Stingier: producing a program that gobbles less heap space
474 <label id="stingier">
475 <p>
476 <nidx>memory, using less heap</nidx>
477 <nidx>space-leaks, avoiding</nidx>
478 <nidx>heap space, using less</nidx>
479 %*                                                                      *
480 %************************************************************************
481
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@...]
487
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.
491
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
496 be required).