[project @ 2004-08-08 17:26:26 by krasimir]
[ghc-hetmet.git] / ghc / docs / users_guide / sooner.sgml
1 <chapter id="sooner-faster-quicker">
2 <title>Advice on: sooner, faster, smaller, thriftier</title>
3
4 <para>Please advise us of other &ldquo;helpful hints&rdquo; that
5 should go here!</para>
6
7 <sect1 id="sooner">
8 <title>Sooner: producing a program more quickly
9 </title>
10
11 <indexterm><primary>compiling faster</primary></indexterm>
12 <indexterm><primary>faster compiling</primary></indexterm>
13
14     <variablelist>
15       <varlistentry>
16         <term>Don't use <option>-O</option> or (especially) <option>-O2</option>:</term>
17         <listitem>
18           <para>By using them, you are telling GHC that you are
19           willing to suffer longer compilation times for
20           better-quality code.</para>
21
22           <para>GHC is surprisingly zippy for normal compilations
23           without <option>-O</option>!</para>
24         </listitem>
25       </varlistentry>
26
27       <varlistentry>
28         <term>Use more memory:</term>
29         <listitem>
30           <para>Within reason, more memory for heap space means less
31           garbage collection for GHC, which means less compilation
32           time.  If you use the <option>-Rghc-timing</option> option,
33           you'll get a garbage-collector report.  (Again, you can use
34           the cheap-and-nasty <option>+RTS -Sstderr -RTS</option>
35           option to send the GC stats straight to standard
36           error.)</para>
37
38           <para>If it says you're using more than 20&percnt; of total
39           time in garbage collecting, then more memory would
40           help.</para>
41
42           <para>If the heap size is approaching the maximum (64M by
43           default), and you have lots of memory, try increasing the
44           maximum with the
45           <option>-M&lt;size&gt;</option><indexterm><primary>-M&lt;size&gt;
46           option</primary></indexterm> option, e.g.: <command>ghc -c
47           -O -M1024m Foo.hs</command>.</para>
48
49           <para>Increasing the default allocation area size used by
50           the compiler's RTS might also help: use the
51           <option>-A&lt;size&gt;</option><indexterm><primary>-A&lt;size&gt;
52           option</primary></indexterm> option.</para>
53
54           <para>If GHC persists in being a bad memory citizen, please
55           report it as a bug.</para>
56         </listitem>
57       </varlistentry>
58
59       <varlistentry>
60         <term>Don't use too much memory!</term>
61         <listitem>
62           <para>As soon as GHC plus its &ldquo;fellow citizens&rdquo;
63           (other processes on your machine) start using more than the
64           <emphasis>real memory</emphasis> on your machine, and the
65           machine starts &ldquo;thrashing,&rdquo; <emphasis>the party
66           is over</emphasis>.  Compile times will be worse than
67           terrible!  Use something like the csh-builtin
68           <command>time</command> command to get a report on how many
69           page faults you're getting.</para>
70
71           <para>If you don't know what virtual memory, thrashing, and
72           page faults are, or you don't know the memory configuration
73           of your machine, <emphasis>don't</emphasis> try to be clever
74           about memory use: you'll just make your life a misery (and
75           for other people, too, probably).</para>
76         </listitem>
77       </varlistentry>
78
79       <varlistentry>
80         <term>Try to use local disks when linking:</term>
81         <listitem>
82           <para>Because Haskell objects and libraries tend to be
83           large, it can take many real seconds to slurp the bits
84           to/from a remote filesystem.</para>
85
86           <para>It would be quite sensible to
87           <emphasis>compile</emphasis> on a fast machine using
88           remotely-mounted disks; then <emphasis>link</emphasis> on a
89           slow machine that had your disks directly mounted.</para>
90         </listitem>
91       </varlistentry>
92
93       <varlistentry>
94         <term>Don't derive/use <function>Read</function> unnecessarily:</term>
95         <listitem>
96           <para>It's ugly and slow.</para>
97         </listitem>
98       </varlistentry>
99
100       <varlistentry>
101         <term>GHC compiles some program constructs slowly:</term>
102         <listitem>
103           <para>Deeply-nested list comprehensions seem to be one such;
104           in the past, very large constant tables were bad,
105           too.</para>
106
107           <para>We'd rather you reported such behaviour as a bug, so
108           that we can try to correct it.</para>
109
110           <para>The part of the compiler that is occasionally prone to
111           wandering off for a long time is the strictness analyser.
112           You can turn this off individually with
113           <option>-fno-strictness</option>.
114           <indexterm><primary>-fno-strictness
115           anti-option</primary></indexterm></para>
116           
117           <para>To figure out which part of the compiler is badly
118           behaved, the
119           <option>-v2</option><indexterm><primary><option>-v</option></primary>
120           </indexterm> option is your friend.</para>
121
122           <para>If your module has big wads of constant data, GHC may
123           produce a huge basic block that will cause the native-code
124           generator's register allocator to founder.  Bring on
125           <option>-fvia-C</option><indexterm><primary>-fvia-C
126           option</primary></indexterm> (not that GCC will be that
127           quick about it, either).</para>
128         </listitem>
129       </varlistentry>
130       
131       <varlistentry>
132         <term>Explicit <literal>import</literal> declarations:</term>
133         <listitem>
134           <para>Instead of saying <literal>import Foo</literal>, say
135           <literal>import Foo (...stuff I want...)</literal> You can
136           get GHC to tell you the minimal set of required imports by
137           using the <option>-ddump-minimal-imports</option> option
138           (see <xref linkend="hi-options"/>).</para>
139
140           <para>Truthfully, the reduction on compilation time will be
141           very small.  However, judicious use of
142           <literal>import</literal> declarations can make a program
143           easier to understand, so it may be a good idea
144           anyway.</para>
145         </listitem>
146       </varlistentry>
147     </variablelist>
148   </sect1>
149
150   <sect1 id="faster">
151     <title>Faster: producing a program that runs quicker</title>
152
153     <indexterm><primary>faster programs, how to produce</primary></indexterm>
154
155     <para>The key tool to use in making your Haskell program run
156     faster are GHC's profiling facilities, described separately in
157     <xref linkend="profiling"/>.  There is <emphasis>no
158     substitute</emphasis> for finding where your program's time/space
159     is <emphasis>really</emphasis> going, as opposed to where you
160     imagine it is going.</para>
161
162     <para>Another point to bear in mind: By far the best way to
163     improve a program's performance <emphasis>dramatically</emphasis>
164     is to use better algorithms.  Once profiling has thrown the
165     spotlight on the guilty time-consumer(s), it may be better to
166     re-think your program than to try all the tweaks listed below.</para>
167
168     <para>Another extremely efficient way to make your program snappy
169     is to use library code that has been Seriously Tuned By Someone
170     Else.  You <emphasis>might</emphasis> be able to write a better
171     quicksort than the one in <literal>Data.List</literal>, but it
172     will take you much longer than typing <literal>import
173     Data.List</literal>.</para>
174
175     <para>Please report any overly-slow GHC-compiled programs.  Since
176     GHC doesn't have any credible competition in the performance
177     department these days it's hard to say what overly-slow means, so
178     just use your judgement!  Of course, if a GHC compiled program
179     runs slower than the same program compiled with NHC or Hugs, then
180     it's definitely a bug.</para>
181
182     <variablelist>
183       <varlistentry>
184         <term>Optimise, using <option>-O</option> or <option>-O2</option>:</term>
185         <listitem>
186           <para>This is the most basic way to make your program go
187           faster.  Compilation time will be slower, especially with
188           <option>-O2</option>.</para>
189
190           <para>At present, <option>-O2</option> is nearly
191           indistinguishable from <option>-O</option>.</para>
192         </listitem>
193       </varlistentry>
194
195       <varlistentry>
196         <term>Compile via C and crank up GCC:</term>
197         <listitem>
198           <para>The native code-generator is designed to be quick, not
199           mind-bogglingly clever.  Better to let GCC have a go, as it
200           tries much harder on register allocation, etc.</para>
201
202           <para>At the moment, if you turn on <option>-O</option> you
203           get GCC instead.  This may change in the future.</para>
204
205           <para>So, when we want very fast code, we use: <option>-O
206           -fvia-C</option>.</para>
207         </listitem>
208       </varlistentry>
209
210       <varlistentry>
211         <term>Overloaded functions are not your friend:</term>
212         <listitem>
213           <para>Haskell's overloading (using type classes) is elegant,
214           neat, etc., etc., but it is death to performance if left to
215           linger in an inner loop.  How can you squash it?</para>
216
217           <variablelist>
218             <varlistentry>
219               <term>Give explicit type signatures:</term>
220               <listitem>
221                 <para>Signatures are the basic trick; putting them on
222                 exported, top-level functions is good
223                 software-engineering practice, anyway.  (Tip: using
224                 <option>-fwarn-missing-signatures</option><indexterm><primary>-fwarn-missing-signatures
225                 option</primary></indexterm> can help enforce good
226                 signature-practice).</para>
227
228                 <para>The automatic specialisation of overloaded
229                 functions (with <option>-O</option>) should take care
230                 of overloaded local and/or unexported functions.</para>
231               </listitem>
232             </varlistentry>
233
234             <varlistentry>
235               <term>Use <literal>SPECIALIZE</literal> pragmas:</term>
236               <listitem>
237                 <indexterm><primary>SPECIALIZE pragma</primary></indexterm>
238                 <indexterm><primary>overloading, death to</primary></indexterm>
239
240                 <para>Specialize the overloading on key functions in
241                 your program.  See <xref linkend="specialize-pragma"/>
242                 and <xref linkend="specialize-instance-pragma"/>.</para>
243               </listitem>
244             </varlistentry>
245
246             <varlistentry>
247               <term>&ldquo;But how do I know where overloading is creeping in?&rdquo;:</term>
248               <listitem>
249                 <para>A low-tech way: grep (search) your interface
250                 files for overloaded type signatures.  You can view
251                 interface files using the
252                 <option>--show-iface</option> option (see <xref
253                 linkend="hi-options"/>).
254
255 <programlisting>
256 % ghc --show-iface Foo.hi | egrep '^[a-z].*::.*=&#62;'
257 </programlisting>
258 </para>
259               </listitem>
260             </varlistentry>
261           </variablelist>
262         </listitem>
263       </varlistentry>
264
265       <varlistentry>
266         <term>Strict functions are your dear friends:</term>
267         <listitem>
268           <para>and, among other things, lazy pattern-matching is your
269           enemy.</para>
270
271           <para>(If you don't know what a &ldquo;strict
272           function&rdquo; is, please consult a functional-programming
273           textbook.  A sentence or two of explanation here probably
274           would not do much good.)</para>
275
276           <para>Consider these two code fragments:
277
278 <programlisting>
279 f (Wibble x y) =  ... # strict
280
281 f arg = let { (Wibble x y) = arg } in ... # lazy
282 </programlisting>
283
284            The former will result in far better code.</para>
285
286           <para>A less contrived example shows the use of
287           <literal>cases</literal> instead of <literal>lets</literal>
288           to get stricter code (a good thing):
289
290 <programlisting>
291 f (Wibble x y)  # beautiful but slow
292   = let
293         (a1, b1, c1) = unpackFoo x
294         (a2, b2, c2) = unpackFoo y
295     in ...
296
297 f (Wibble x y)  # ugly, and proud of it
298   = case (unpackFoo x) of { (a1, b1, c1) -&#62;
299     case (unpackFoo y) of { (a2, b2, c2) -&#62;
300     ...
301     }}
302 </programlisting>
303
304           </para>
305         </listitem>
306       </varlistentry>
307
308       <varlistentry>
309         <term>GHC loves single-constructor data-types:</term>
310         <listitem>
311           <para>It's all the better if a function is strict in a
312           single-constructor type (a type with only one
313           data-constructor; for example, tuples are single-constructor
314           types).</para>
315         </listitem>
316       </varlistentry>
317
318       <varlistentry>
319         <term>Newtypes are better than datatypes:</term>
320         <listitem>
321           <para>If your datatype has a single constructor with a
322           single field, use a <literal>newtype</literal> declaration
323           instead of a <literal>data</literal> declaration.  The
324           <literal>newtype</literal> will be optimised away in most
325           cases.</para>
326         </listitem>
327       </varlistentry>
328
329       <varlistentry>
330         <term>&ldquo;How do I find out a function's strictness?&rdquo;</term>
331         <listitem>
332           <para>Don't guess&mdash;look it up.</para>
333
334           <para>Look for your function in the interface file, then for
335           the third field in the pragma; it should say
336           <literal>&lowbar;&lowbar;S &lt;string&gt;</literal>.  The
337           <literal>&lt;string&gt;</literal> gives the strictness of
338           the function's arguments.  <function>L</function> is lazy
339           (bad), <function>S</function> and <function>E</function> are
340           strict (good), <function>P</function> is
341           &ldquo;primitive&rdquo; (good), <function>U(...)</function>
342           is strict and &ldquo;unpackable&rdquo; (very good), and
343           <function>A</function> is absent (very good).</para>
344
345           <para>For an &ldquo;unpackable&rdquo;
346           <function>U(...)</function> argument, the info inside tells
347           the strictness of its components.  So, if the argument is a
348           pair, and it says <function>U(AU(LSS))</function>, that
349           means &ldquo;the first component of the pair isn't used; the
350           second component is itself unpackable, with three components
351           (lazy in the first, strict in the second \&#38;
352           third).&rdquo;</para>
353
354           <para>If the function isn't exported, just compile with the
355           extra flag <option>-ddump-simpl</option>; next to the
356           signature for any binder, it will print the self-same
357           pragmatic information as would be put in an interface file.
358           (Besides, Core syntax is fun to look at!)</para>
359         </listitem>
360       </varlistentry>
361
362       <varlistentry>
363         <term>Force key functions to be <literal>INLINE</literal>d (esp. monads):</term>
364         <listitem>
365           <para>Placing <literal>INLINE</literal> pragmas on certain
366           functions that are used a lot can have a dramatic effect.
367           See <xref linkend="inline-pragma"/>.</para>
368         </listitem>
369       </varlistentry>
370
371       <varlistentry>
372         <term>Explicit <literal>export</literal> list:</term>
373         <listitem>
374           <para>If you do not have an explicit export list in a
375           module, GHC must assume that everything in that module will
376           be exported.  This has various pessimising effects.  For
377           example, if a bit of code is actually
378           <emphasis>unused</emphasis> (perhaps because of unfolding
379           effects), GHC will not be able to throw it away, because it
380           is exported and some other module may be relying on its
381           existence.</para>
382
383           <para>GHC can be quite a bit more aggressive with pieces of
384           code if it knows they are not exported.</para>
385         </listitem>
386       </varlistentry>
387
388       <varlistentry>
389         <term>Look at the Core syntax!</term>
390         <listitem>
391           <para>(The form in which GHC manipulates your code.)  Just
392           run your compilation with <option>-ddump-simpl</option>
393           (don't forget the <option>-O</option>).</para>
394
395           <para>If profiling has pointed the finger at particular
396           functions, look at their Core code.  <literal>lets</literal>
397           are bad, <literal>cases</literal> are good, dictionaries
398           (<literal>d.&lt;Class&gt;.&lt;Unique&gt;</literal>) &lsqb;or
399           anything overloading-ish&rsqb; are bad, nested lambdas are
400           bad, explicit data constructors are good, primitive
401           operations (e.g., <literal>eqInt&num;</literal>) are
402           good,&hellip;</para>
403         </listitem>
404       </varlistentry>
405
406       <varlistentry>
407         <term>Use strictness annotations:</term>
408         <listitem>
409           <para>Putting a strictness annotation ('!') on a constructor
410           field helps in two ways: it adds strictness to the program,
411           which gives the strictness analyser more to work with, and
412           it might help to reduce space leaks.</para>
413
414           <para>It can also help in a third way: when used with
415           <option>-funbox-strict-fields</option> (see <xref
416           linkend="options-f"/>), a strict field can be unpacked or
417           unboxed in the constructor, and one or more levels of
418           indirection may be removed.  Unpacking only happens for
419           single-constructor datatypes (<literal>Int</literal> is a
420           good candidate, for example).</para>
421
422           <para>Using <option>-funbox-strict-fields</option> is only
423           really a good idea in conjunction with <option>-O</option>,
424           because otherwise the extra packing and unpacking won't be
425           optimised away.  In fact, it is possible that
426           <option>-funbox-strict-fields</option> may worsen
427           performance even <emphasis>with</emphasis>
428           <option>-O</option>, but this is unlikely (let us know if it
429           happens to you).</para>
430         </listitem>
431       </varlistentry>
432
433       <varlistentry>
434         <term>Use unboxed types (a GHC extension):</term>
435         <listitem>
436           <para>When you are <emphasis>really</emphasis> desperate for
437           speed, and you want to get right down to the &ldquo;raw
438           bits.&rdquo; Please see <xref linkend="glasgow-unboxed"/> for
439           some information about using unboxed types.</para>
440
441           <para>Before resorting to explicit unboxed types, try using
442           strict constructor fields and
443           <option>-funbox-strict-fields</option> first (see above).
444           That way, your code stays portable.</para>
445         </listitem>
446       </varlistentry>
447
448       <varlistentry>
449         <term>Use <literal>foreign import</literal> (a GHC extension) to plug into fast libraries:</term>
450         <listitem>
451           <para>This may take real work, but&hellip; There exist piles
452           of massively-tuned library code, and the best thing is not
453           to compete with it, but link with it.</para>
454
455           <para><xref linkend="ffi"/> describes the foreign function
456           interface.</para>
457         </listitem>
458       </varlistentry>
459
460       <varlistentry>
461         <term>Don't use <literal>Float</literal>s:</term>
462         <listitem>
463           <para>If you're using <literal>Complex</literal>, definitely
464           use <literal>Complex Double</literal> rather than
465           <literal>Complex Float</literal> (the former is specialised
466           heavily, but the latter isn't).</para>
467
468           <para><literal>Floats</literal> (probably 32-bits) are
469           almost always a bad idea, anyway, unless you Really Know
470           What You Are Doing.  Use <literal>Double</literal>s.
471           There's rarely a speed disadvantage&mdash;modern machines
472           will use the same floating-point unit for both.  With
473           <literal>Double</literal>s, you are much less likely to hang
474           yourself with numerical errors.</para>
475
476           <para>One time when <literal>Float</literal> might be a good
477           idea is if you have a <emphasis>lot</emphasis> of them, say
478           a giant array of <literal>Float</literal>s.  They take up
479           half the space in the heap compared to
480           <literal>Doubles</literal>.  However, this isn't true on a
481           64-bit machine.</para>
482         </listitem>
483       </varlistentry>
484
485       <varlistentry>
486         <term>Use unboxed arrays (<literal>UArray</literal>)</term>
487         <listitem>
488           <para>GHC supports arrays of unboxed elements, for several
489           basic arithmetic element types including
490           <literal>Int</literal> and <literal>Char</literal>: see the
491           <literal>Data.Array.Unboxed</literal> library for details.
492           These arrays are likely to be much faster than using
493           standard Haskell 98 arrays from the
494           <literal>Data.Array</literal> library.</para>
495         </listitem>
496       </varlistentry>
497
498       <varlistentry>
499         <term>Use a bigger heap!</term>
500         <listitem>
501           <para>If your program's GC stats
502           (<option>-S</option><indexterm><primary>-S RTS
503           option</primary></indexterm> RTS option) indicate that it's
504           doing lots of garbage-collection (say, more than 20&percnt;
505           of execution time), more memory might help&mdash;with the
506           <option>-M&lt;size&gt;</option><indexterm><primary>-M&lt;size&gt;
507           RTS option</primary></indexterm> or
508           <option>-A&lt;size&gt;</option><indexterm><primary>-A&lt;size&gt;
509           RTS option</primary></indexterm> RTS options (see <xref
510           linkend="rts-options-gc"/>).</para>
511
512           <para>This is especially important if your program uses a
513           lot of mutable arrays of pointers or mutable variables
514           (i.e. <literal>STArray</literal>,
515           <literal>IOArray</literal>, <literal>STRef</literal> and
516           <literal>IORef</literal>, but not <literal>UArray</literal>,
517           <literal>STUArray</literal> or <literal>IOUArray</literal>).
518           GHC's garbage collector currently scans these objects on
519           every collection, so your program won't benefit from
520           generational GC in the normal way if you use lots of
521           these.  Increasing the heap size to reduce the number of
522           collections will probably help.</para>
523         </listitem>
524       </varlistentry>
525     </variablelist>
526
527 </sect1>
528
529 <sect1 id="smaller">
530 <title>Smaller: producing a program that is smaller
531 </title>
532
533 <para>
534 <indexterm><primary>smaller programs, how to produce</primary></indexterm>
535 </para>
536
537 <para>
538 Decrease the &ldquo;go-for-it&rdquo; threshold for unfolding smallish
539 expressions.  Give a
540 <option>-funfolding-use-threshold0</option><indexterm><primary>-funfolding-use-threshold0
541 option</primary></indexterm> option for the extreme case. (&ldquo;Only unfoldings with
542 zero cost should proceed.&rdquo;)  Warning: except in certain specialised
543 cases (like Happy parsers) this is likely to actually
544 <emphasis>increase</emphasis> the size of your program, because unfolding
545 generally enables extra simplifying optimisations to be performed.
546 </para>
547
548 <para>
549 Avoid <function>Read</function>.
550 </para>
551
552 <para>
553 Use <literal>strip</literal> on your executables.
554 </para>
555
556 </sect1>
557
558 <sect1 id="thriftier">
559 <title>Thriftier: producing a program that gobbles less heap space
560 </title>
561
562 <para>
563 <indexterm><primary>memory, using less heap</primary></indexterm>
564 <indexterm><primary>space-leaks, avoiding</primary></indexterm>
565 <indexterm><primary>heap space, using less</primary></indexterm>
566 </para>
567
568 <para>
569 &ldquo;I think I have a space leak&hellip;&rdquo; Re-run your program
570 with <option>+RTS -Sstderr</option>, and remove all doubt!  (You'll
571 see the heap usage get bigger and bigger&hellip;)
572 &lsqb;Hmmm&hellip;this might be even easier with the
573 <option>-G1</option> RTS option; so&hellip; <command>./a.out +RTS
574 -Sstderr -G1</command>...]
575 <indexterm><primary>-G RTS option</primary></indexterm>
576 <indexterm><primary>-Sstderr RTS option</primary></indexterm>
577 </para>
578
579 <para>
580 Once again, the profiling facilities (<xref linkend="profiling"/>) are
581 the basic tool for demystifying the space behaviour of your program.
582 </para>
583
584 <para>
585 Strict functions are good for space usage, as they are for time, as
586 discussed in the previous section.  Strict functions get right down to
587 business, rather than filling up the heap with closures (the system's
588 notes to itself about how to evaluate something, should it eventually
589 be required).
590 </para>
591
592 </sect1>
593
594 </chapter>
595
596 <!-- Emacs stuff:
597      ;;; Local Variables: ***
598      ;;; mode: sgml ***
599      ;;; sgml-parent-document: ("users_guide.sgml" "book" "chapter") ***
600      ;;; End: ***
601  -->