Fix the prof_scc.png image in the profiling section (#3694)
[ghc-hetmet.git] / docs / users_guide / profiling.xml
1 <?xml version="1.0" encoding="iso-8859-1"?>
2 <chapter id="profiling">
3   <title>Profiling</title>
4   <indexterm><primary>profiling</primary>
5   </indexterm>
6   <indexterm><primary>cost-centre profiling</primary></indexterm>
7
8   <para> Glasgow Haskell comes with a time and space profiling
9   system. Its purpose is to help you improve your understanding of
10   your program's execution behaviour, so you can improve it.</para>
11   
12   <para> Any comments, suggestions and/or improvements you have are
13   welcome.  Recommended &ldquo;profiling tricks&rdquo; would be
14   especially cool! </para>
15
16   <para>Profiling a program is a three-step process:</para>
17
18   <orderedlist>
19     <listitem>
20       <para> Re-compile your program for profiling with the
21       <literal>-prof</literal> option, and probably one of the
22       <literal>-auto</literal> or <literal>-auto-all</literal>
23       options.  These options are described in more detail in <xref
24       linkend="prof-compiler-options"/> </para>
25       <indexterm><primary><literal>-prof</literal></primary>
26       </indexterm>
27       <indexterm><primary><literal>-auto</literal></primary>
28       </indexterm>
29       <indexterm><primary><literal>-auto-all</literal></primary>
30       </indexterm>
31     </listitem>
32
33     <listitem>
34       <para> Run your program with one of the profiling options, eg.
35       <literal>+RTS -p -RTS</literal>.  This generates a file of
36       profiling information.  Note that multi-processor execution
37       (e.g. <literal>+RTS -N2</literal>) is not supported while
38       profiling.</para>
39       <indexterm><primary><option>-p</option></primary><secondary>RTS
40       option</secondary></indexterm>
41     </listitem>
42       
43     <listitem>
44       <para> Examine the generated profiling information, using one of
45       GHC's profiling tools.  The tool to use will depend on the kind
46       of profiling information generated.</para>
47     </listitem>
48     
49   </orderedlist>
50   
51   <sect1 id="cost-centres">
52     <title>Cost centres and cost-centre stacks</title>
53     
54     <para>GHC's profiling system assigns <firstterm>costs</firstterm>
55     to <firstterm>cost centres</firstterm>.  A cost is simply the time
56     or space required to evaluate an expression.  Cost centres are
57     program annotations around expressions; all costs incurred by the
58     annotated expression are assigned to the enclosing cost centre.
59     Furthermore, GHC will remember the stack of enclosing cost centres
60     for any given expression at run-time and generate a call-graph of
61     cost attributions.</para>
62
63     <para>Let's take a look at an example:</para>
64
65     <programlisting>
66 main = print (nfib 25)
67 nfib n = if n &lt; 2 then 1 else nfib (n-1) + nfib (n-2)
68 </programlisting>
69
70     <para>Compile and run this program as follows:</para>
71
72     <screen>
73 $ ghc -prof -auto-all -o Main Main.hs
74 $ ./Main +RTS -p
75 121393
76 $
77 </screen>
78
79     <para>When a GHC-compiled program is run with the
80     <option>-p</option> RTS option, it generates a file called
81     <filename>&lt;prog&gt;.prof</filename>.  In this case, the file
82     will contain something like this:</para>
83
84 <screen>
85           Fri May 12 14:06 2000 Time and Allocation Profiling Report  (Final)
86
87            Main +RTS -p -RTS
88
89         total time  =        0.14 secs   (7 ticks @ 20 ms)
90         total alloc =   8,741,204 bytes  (excludes profiling overheads)
91
92 COST CENTRE          MODULE     %time %alloc
93
94 nfib                 Main       100.0  100.0
95
96
97                                               individual     inherited
98 COST CENTRE              MODULE      entries %time %alloc   %time %alloc
99
100 MAIN                     MAIN             0    0.0   0.0    100.0 100.0
101  main                    Main             0    0.0   0.0      0.0   0.0
102  CAF                     PrelHandle       3    0.0   0.0      0.0   0.0
103  CAF                     PrelAddr         1    0.0   0.0      0.0   0.0
104  CAF                     Main             6    0.0   0.0    100.0 100.0
105   main                   Main             1    0.0   0.0    100.0 100.0
106    nfib                  Main        242785  100.0 100.0    100.0 100.0
107 </screen>
108
109
110     <para>The first part of the file gives the program name and
111     options, and the total time and total memory allocation measured
112     during the run of the program (note that the total memory
113     allocation figure isn't the same as the amount of
114     <emphasis>live</emphasis> memory needed by the program at any one
115     time; the latter can be determined using heap profiling, which we
116     will describe shortly).</para>
117
118     <para>The second part of the file is a break-down by cost centre
119     of the most costly functions in the program.  In this case, there
120     was only one significant function in the program, namely
121     <function>nfib</function>, and it was responsible for 100&percnt;
122     of both the time and allocation costs of the program.</para>
123
124     <para>The third and final section of the file gives a profile
125     break-down by cost-centre stack.  This is roughly a call-graph
126     profile of the program.  In the example above, it is clear that
127     the costly call to <function>nfib</function> came from
128     <function>main</function>.</para>
129
130     <para>The time and allocation incurred by a given part of the
131     program is displayed in two ways: &ldquo;individual&rdquo;, which
132     are the costs incurred by the code covered by this cost centre
133     stack alone, and &ldquo;inherited&rdquo;, which includes the costs
134     incurred by all the children of this node.</para>
135
136     <para>The usefulness of cost-centre stacks is better demonstrated
137     by  modifying the example slightly:</para>
138
139     <programlisting>
140 main = print (f 25 + g 25)
141 f n  = nfib n
142 g n  = nfib (n `div` 2)
143 nfib n = if n &lt; 2 then 1 else nfib (n-1) + nfib (n-2)
144 </programlisting>
145
146     <para>Compile and run this program as before, and take a look at
147     the new profiling results:</para>
148
149 <screen>
150 COST CENTRE              MODULE         scc  %time %alloc   %time %alloc
151
152 MAIN                     MAIN             0    0.0   0.0    100.0 100.0
153  main                    Main             0    0.0   0.0      0.0   0.0
154  CAF                     PrelHandle       3    0.0   0.0      0.0   0.0
155  CAF                     PrelAddr         1    0.0   0.0      0.0   0.0
156  CAF                     Main             9    0.0   0.0    100.0 100.0
157   main                   Main             1    0.0   0.0    100.0 100.0
158    g                     Main             1    0.0   0.0      0.0   0.2
159     nfib                 Main           465    0.0   0.2      0.0   0.2
160    f                     Main             1    0.0   0.0    100.0  99.8
161     nfib                 Main        242785  100.0  99.8    100.0  99.8
162 </screen>
163
164     <para>Now although we had two calls to <function>nfib</function>
165     in the program, it is immediately clear that it was the call from
166     <function>f</function> which took all the time.</para>
167
168     <para>The actual meaning of the various columns in the output is:</para>
169
170     <variablelist>
171       <varlistentry>
172         <term>entries</term>
173         <listitem>
174           <para>The number of times this particular point in the call
175           graph was entered.</para>
176         </listitem>
177       </varlistentry>
178
179       <varlistentry>
180         <term>individual &percnt;time</term>
181         <listitem>
182           <para>The percentage of the total run time of the program
183           spent at this point in the call graph.</para>
184         </listitem>
185       </varlistentry>
186
187       <varlistentry>
188         <term>individual &percnt;alloc</term>
189         <listitem>
190           <para>The percentage of the total memory allocations
191           (excluding profiling overheads) of the program made by this
192           call.</para>
193         </listitem>
194       </varlistentry>
195
196       <varlistentry>
197         <term>inherited &percnt;time</term>
198         <listitem>
199           <para>The percentage of the total run time of the program
200           spent below this point in the call graph.</para>
201         </listitem>
202       </varlistentry>
203
204       <varlistentry>
205         <term>inherited &percnt;alloc</term>
206         <listitem>
207           <para>The percentage of the total memory allocations
208           (excluding profiling overheads) of the program made by this
209           call and all of its sub-calls.</para>
210         </listitem>
211       </varlistentry>
212     </variablelist>
213
214     <para>In addition you can use the <option>-P</option> RTS option
215     <indexterm><primary><option>-P</option></primary></indexterm> to
216     get the following additional information:</para>
217
218     <variablelist>
219       <varlistentry>
220         <term><literal>ticks</literal></term>
221         <listitem>
222           <para>The raw number of time &ldquo;ticks&rdquo; which were
223           attributed to this cost-centre; from this, we get the
224           <literal>&percnt;time</literal> figure mentioned
225           above.</para>
226         </listitem>
227       </varlistentry>
228
229       <varlistentry>
230         <term><literal>bytes</literal></term>
231         <listitem>
232           <para>Number of bytes allocated in the heap while in this
233           cost-centre; again, this is the raw number from which we get
234           the <literal>&percnt;alloc</literal> figure mentioned
235           above.</para>
236         </listitem>
237       </varlistentry>
238     </variablelist>
239
240     <para>What about recursive functions, and mutually recursive
241     groups of functions?  Where are the costs attributed?  Well,
242     although GHC does keep information about which groups of functions
243     called each other recursively, this information isn't displayed in
244     the basic time and allocation profile, instead the call-graph is
245     flattened into a tree.</para>
246
247     <sect2><title>Inserting cost centres by hand</title>
248
249       <para>Cost centres are just program annotations.  When you say
250       <option>-auto-all</option> to the compiler, it automatically
251       inserts a cost centre annotation around every top-level function
252       in your program, but you are entirely free to add the cost
253       centre annotations yourself.</para>
254
255       <para>The syntax of a cost centre annotation is</para>
256
257       <programlisting>
258      {-# SCC "name" #-} &lt;expression&gt;
259 </programlisting>
260
261       <para>where <literal>"name"</literal> is an arbitrary string,
262       that will become the name of your cost centre as it appears
263       in the profiling output, and
264       <literal>&lt;expression&gt;</literal> is any Haskell
265       expression.  An <literal>SCC</literal> annotation extends as
266       far to the right as possible when parsing. (SCC stands for "Set
267       Cost Centre").</para>
268
269       <para>Here is an example of a program with a couple of SCCs:</para>
270
271 <programlisting>
272 main :: IO ()
273 main = do let xs = {-# SCC "X" #-} [1..1000000]
274           let ys = {-# SCC "Y" #-} [1..2000000]
275           print $ last xs
276           print $ last $ init xs
277           print $ last ys
278           print $ last $ init ys
279 </programlisting>
280
281       <para>which gives this heap profile when run:</para>
282
283       <imagedata fileref="prof_scc.png"/>
284
285     </sect2>
286
287     <sect2 id="prof-rules">
288       <title>Rules for attributing costs</title>
289
290       <para>The cost of evaluating any expression in your program is
291       attributed to a cost-centre stack using the following rules:</para>
292
293       <itemizedlist>
294         <listitem>
295           <para>If the expression is part of the
296           <firstterm>one-off</firstterm> costs of evaluating the
297           enclosing top-level definition, then costs are attributed to
298           the stack of lexically enclosing <literal>SCC</literal>
299           annotations on top of the special <literal>CAF</literal>
300           cost-centre. </para>
301         </listitem>
302
303         <listitem>
304           <para>Otherwise, costs are attributed to the stack of
305           lexically-enclosing <literal>SCC</literal> annotations,
306           appended to the cost-centre stack in effect at the
307           <firstterm>call site</firstterm> of the current top-level
308           definition<footnote> <para>The call-site is just the place
309           in the source code which mentions the particular function or
310           variable.</para></footnote>.  Notice that this is a recursive
311           definition.</para>
312         </listitem>
313
314         <listitem>
315           <para>Time spent in foreign code (see <xref linkend="ffi"/>)
316           is always attributed to the cost centre in force at the
317           Haskell call-site of the foreign function.</para>
318         </listitem>
319       </itemizedlist>
320
321       <para>What do we mean by one-off costs?  Well, Haskell is a lazy
322       language, and certain expressions are only ever evaluated once.
323       For example, if we write:</para>
324
325       <programlisting>
326 x = nfib 25
327 </programlisting>
328
329       <para>then <varname>x</varname> will only be evaluated once (if
330       at all), and subsequent demands for <varname>x</varname> will
331       immediately get to see the cached result.  The definition
332       <varname>x</varname> is called a CAF (Constant Applicative
333       Form), because it has no arguments.</para>
334
335       <para>For the purposes of profiling, we say that the expression
336       <literal>nfib 25</literal> belongs to the one-off costs of
337       evaluating <varname>x</varname>.</para>
338
339       <para>Since one-off costs aren't strictly speaking part of the
340       call-graph of the program, they are attributed to a special
341       top-level cost centre, <literal>CAF</literal>.  There may be one
342       <literal>CAF</literal> cost centre for each module (the
343       default), or one for each top-level definition with any one-off
344       costs (this behaviour can be selected by giving GHC the
345       <option>-caf-all</option> flag).</para>
346
347       <indexterm><primary><literal>-caf-all</literal></primary>
348       </indexterm>
349
350       <para>If you think you have a weird profile, or the call-graph
351       doesn't look like you expect it to, feel free to send it (and
352       your program) to us at
353       <email>glasgow-haskell-bugs@haskell.org</email>.</para>
354     </sect2>
355   </sect1>
356
357   <sect1 id="prof-compiler-options">
358     <title>Compiler options for profiling</title>
359
360     <indexterm><primary>profiling</primary><secondary>options</secondary></indexterm>
361     <indexterm><primary>options</primary><secondary>for profiling</secondary></indexterm>
362
363     <variablelist>
364       <varlistentry>
365         <term>
366           <option>-prof</option>:
367           <indexterm><primary><option>-prof</option></primary></indexterm>
368         </term>
369         <listitem>
370           <para> To make use of the profiling system
371           <emphasis>all</emphasis> modules must be compiled and linked
372           with the <option>-prof</option> option. Any
373           <literal>SCC</literal> annotations you've put in your source
374           will spring to life.</para>
375
376           <para> Without a <option>-prof</option> option, your
377           <literal>SCC</literal>s are ignored; so you can compile
378           <literal>SCC</literal>-laden code without changing
379           it.</para>
380         </listitem>
381       </varlistentry>
382     </variablelist>
383       
384     <para>There are a few other profiling-related compilation options.
385     Use them <emphasis>in addition to</emphasis>
386     <option>-prof</option>.  These do not have to be used consistently
387     for all modules in a program.</para>
388
389     <variablelist>
390       <varlistentry>
391         <term>
392           <option>-auto</option>:
393           <indexterm><primary><option>-auto</option></primary></indexterm>
394           <indexterm><primary>cost centres</primary><secondary>automatically inserting</secondary></indexterm>
395         </term>
396         <listitem>
397           <para> GHC will automatically add
398           <function>&lowbar;scc&lowbar;</function> constructs for all
399           top-level, exported functions.</para>
400         </listitem>
401       </varlistentry>
402       
403       <varlistentry>
404         <term>
405           <option>-auto-all</option>:
406           <indexterm><primary><option>-auto-all</option></primary></indexterm>
407         </term>
408         <listitem>
409           <para> <emphasis>All</emphasis> top-level functions,
410           exported or not, will be automatically
411           <function>&lowbar;scc&lowbar;</function>'d.</para>
412         </listitem>
413       </varlistentry>
414
415       <varlistentry>
416         <term>
417           <option>-caf-all</option>:
418           <indexterm><primary><option>-caf-all</option></primary></indexterm>
419         </term>
420         <listitem>
421           <para> The costs of all CAFs in a module are usually
422           attributed to one &ldquo;big&rdquo; CAF cost-centre. With
423           this option, all CAFs get their own cost-centre.  An
424           &ldquo;if all else fails&rdquo; option&hellip;</para>
425         </listitem>
426       </varlistentry>
427
428       <varlistentry>
429         <term>
430           <option>-ignore-scc</option>:
431           <indexterm><primary><option>-ignore-scc</option></primary></indexterm>
432         </term>
433         <listitem>
434           <para>Ignore any <function>&lowbar;scc&lowbar;</function>
435           constructs, so a module which already has
436           <function>&lowbar;scc&lowbar;</function>s can be compiled
437           for profiling with the annotations ignored.</para>
438         </listitem>
439       </varlistentry>
440
441     </variablelist>
442
443   </sect1>
444
445   <sect1 id="prof-time-options">
446     <title>Time and allocation profiling</title>
447
448     <para>To generate a time and allocation profile, give one of the
449     following RTS options to the compiled program when you run it (RTS
450     options should be enclosed between <literal>+RTS...-RTS</literal>
451     as usual):</para>
452
453     <variablelist>
454       <varlistentry>
455         <term>
456           <option>-p</option> or <option>-P</option>:
457           <indexterm><primary><option>-p</option></primary></indexterm>
458           <indexterm><primary><option>-P</option></primary></indexterm>
459           <indexterm><primary>time profile</primary></indexterm>
460         </term>
461         <listitem>
462           <para>The <option>-p</option> option produces a standard
463           <emphasis>time profile</emphasis> report.  It is written
464           into the file
465           <filename><replaceable>program</replaceable>.prof</filename>.</para>
466
467           <para>The <option>-P</option> option produces a more
468           detailed report containing the actual time and allocation
469           data as well.  (Not used much.)</para>
470         </listitem>
471       </varlistentry>
472
473       <varlistentry>
474         <term>
475           <option>-xc</option>
476           <indexterm><primary><option>-xc</option></primary><secondary>RTS option</secondary></indexterm>
477         </term>
478         <listitem>
479           <para>This option makes use of the extra information
480           maintained by the cost-centre-stack profiler to provide
481           useful information about the location of runtime errors.
482           See <xref linkend="rts-options-debugging"/>.</para>
483         </listitem>
484       </varlistentry>
485
486     </variablelist>
487     
488   </sect1>
489
490   <sect1 id="prof-heap">
491     <title>Profiling memory usage</title>
492
493     <para>In addition to profiling the time and allocation behaviour
494     of your program, you can also generate a graph of its memory usage
495     over time.  This is useful for detecting the causes of
496     <firstterm>space leaks</firstterm>, when your program holds on to
497     more memory at run-time that it needs to.  Space leaks lead to
498     longer run-times due to heavy garbage collector activity, and may
499     even cause the program to run out of memory altogether.</para>
500
501     <para>To generate a heap profile from your program:</para>
502
503     <orderedlist>
504       <listitem>
505         <para>Compile the program for profiling (<xref
506         linkend="prof-compiler-options"/>).</para>
507       </listitem>
508       <listitem>
509         <para>Run it with one of the heap profiling options described
510         below (eg. <option>-hc</option> for a basic producer profile).
511         This generates the file
512         <filename><replaceable>prog</replaceable>.hp</filename>.</para>
513       </listitem>
514       <listitem>
515         <para>Run <command>hp2ps</command> to produce a Postscript
516         file,
517         <filename><replaceable>prog</replaceable>.ps</filename>.  The
518         <command>hp2ps</command> utility is described in detail in
519         <xref linkend="hp2ps"/>.</para> 
520       </listitem>
521       <listitem>
522         <para>Display the heap profile using a postscript viewer such
523         as <application>Ghostview</application>, or print it out on a
524         Postscript-capable printer.</para>
525       </listitem>
526     </orderedlist>
527
528     <para>You might also want to take a look
529       at <ulink url="http://www.haskell.org/haskellwiki/Hp2any">hp2any</ulink>,
530       a more advanced suite of tools (not distributed with GHC) for
531       displaying heap profiles.</para>
532
533     <sect2 id="rts-options-heap-prof">
534       <title>RTS options for heap profiling</title>
535
536       <para>There are several different kinds of heap profile that can
537       be generated.  All the different profile types yield a graph of
538       live heap against time, but they differ in how the live heap is
539       broken down into bands.  The following RTS options select which
540       break-down to use:</para>
541
542       <variablelist>
543         <varlistentry>
544           <term>
545             <option>-hc</option>
546             <indexterm><primary><option>-hc</option></primary><secondary>RTS option</secondary></indexterm>
547           </term>
548           <listitem>
549             <para>Breaks down the graph by the cost-centre stack which
550             produced the data.</para>
551           </listitem>
552         </varlistentry>
553
554         <varlistentry>
555           <term>
556             <option>-hm</option>
557             <indexterm><primary><option>-hm</option></primary><secondary>RTS option</secondary></indexterm>
558           </term>
559           <listitem>
560             <para>Break down the live heap by the module containing
561             the code which produced the data.</para>
562           </listitem>
563         </varlistentry>
564
565         <varlistentry>
566           <term>
567             <option>-hd</option>
568             <indexterm><primary><option>-hd</option></primary><secondary>RTS option</secondary></indexterm>
569           </term>
570           <listitem>
571             <para>Breaks down the graph by <firstterm>closure
572             description</firstterm>.  For actual data, the description
573             is just the constructor name, for other closures it is a
574             compiler-generated string identifying the closure.</para>
575           </listitem>
576         </varlistentry>
577
578         <varlistentry>
579           <term>
580             <option>-hy</option>
581             <indexterm><primary><option>-hy</option></primary><secondary>RTS option</secondary></indexterm>
582           </term>
583           <listitem>
584             <para>Breaks down the graph by
585             <firstterm>type</firstterm>.  For closures which have
586             function type or unknown/polymorphic type, the string will
587             represent an approximation to the actual type.</para>
588           </listitem>
589         </varlistentry>
590         
591         <varlistentry>
592           <term>
593             <option>-hr</option>
594             <indexterm><primary><option>-hr</option></primary><secondary>RTS option</secondary></indexterm>
595           </term>
596           <listitem>
597             <para>Break down the graph by <firstterm>retainer
598             set</firstterm>.  Retainer profiling is described in more
599             detail below (<xref linkend="retainer-prof"/>).</para>
600           </listitem>
601         </varlistentry>
602
603         <varlistentry>
604           <term>
605             <option>-hb</option>
606             <indexterm><primary><option>-hb</option></primary><secondary>RTS option</secondary></indexterm>
607           </term>
608           <listitem>
609             <para>Break down the graph by
610             <firstterm>biography</firstterm>.  Biographical profiling
611             is described in more detail below (<xref
612             linkend="biography-prof"/>).</para>
613           </listitem>
614         </varlistentry>
615       </variablelist>
616
617       <para>In addition, the profile can be restricted to heap data
618       which satisfies certain criteria - for example, you might want
619       to display a profile by type but only for data produced by a
620       certain module, or a profile by retainer for a certain type of
621       data.  Restrictions are specified as follows:</para>
622       
623       <variablelist>
624         <varlistentry>
625           <term>
626             <option>-hc</option><replaceable>name</replaceable>,...
627             <indexterm><primary><option>-hc</option></primary><secondary>RTS option</secondary></indexterm>
628           </term>
629           <listitem>
630             <para>Restrict the profile to closures produced by
631             cost-centre stacks with one of the specified cost centres
632             at the top.</para>
633           </listitem>
634         </varlistentry>
635
636         <varlistentry>
637           <term>
638             <option>-hC</option><replaceable>name</replaceable>,...
639             <indexterm><primary><option>-hC</option></primary><secondary>RTS option</secondary></indexterm>
640           </term>
641           <listitem>
642             <para>Restrict the profile to closures produced by
643             cost-centre stacks with one of the specified cost centres
644             anywhere in the stack.</para>
645           </listitem>
646         </varlistentry>
647
648         <varlistentry>
649           <term>
650             <option>-hm</option><replaceable>module</replaceable>,...
651             <indexterm><primary><option>-hm</option></primary><secondary>RTS option</secondary></indexterm>
652           </term>
653           <listitem>
654             <para>Restrict the profile to closures produced by the
655             specified modules.</para>
656           </listitem>
657         </varlistentry>
658
659         <varlistentry>
660           <term>
661             <option>-hd</option><replaceable>desc</replaceable>,...
662             <indexterm><primary><option>-hd</option></primary><secondary>RTS option</secondary></indexterm>
663           </term>
664           <listitem>
665             <para>Restrict the profile to closures with the specified
666             description strings.</para>
667           </listitem>
668         </varlistentry>
669
670         <varlistentry>
671           <term>
672             <option>-hy</option><replaceable>type</replaceable>,...
673             <indexterm><primary><option>-hy</option></primary><secondary>RTS option</secondary></indexterm>
674           </term>
675           <listitem>
676             <para>Restrict the profile to closures with the specified
677             types.</para>
678           </listitem>
679         </varlistentry>
680         
681         <varlistentry>
682           <term>
683             <option>-hr</option><replaceable>cc</replaceable>,...
684             <indexterm><primary><option>-hr</option></primary><secondary>RTS option</secondary></indexterm>
685           </term>
686           <listitem>
687             <para>Restrict the profile to closures with retainer sets
688             containing cost-centre stacks with one of the specified
689             cost centres at the top.</para>
690           </listitem>
691         </varlistentry>
692
693         <varlistentry>
694           <term>
695             <option>-hb</option><replaceable>bio</replaceable>,...
696             <indexterm><primary><option>-hb</option></primary><secondary>RTS option</secondary></indexterm>
697           </term>
698           <listitem>
699             <para>Restrict the profile to closures with one of the
700             specified biographies, where
701             <replaceable>bio</replaceable> is one of
702             <literal>lag</literal>, <literal>drag</literal>,
703             <literal>void</literal>, or <literal>use</literal>.</para>
704           </listitem>
705         </varlistentry>
706       </variablelist>
707
708       <para>For example, the following options will generate a
709       retainer profile restricted to <literal>Branch</literal> and
710       <literal>Leaf</literal> constructors:</para>
711
712 <screen>
713 <replaceable>prog</replaceable> +RTS -hr -hdBranch,Leaf
714 </screen>
715
716       <para>There can only be one "break-down" option
717       (eg. <option>-hr</option> in the example above), but there is no
718       limit on the number of further restrictions that may be applied.
719       All the options may be combined, with one exception: GHC doesn't
720       currently support mixing the <option>-hr</option> and
721       <option>-hb</option> options.</para>
722
723       <para>There are three more options which relate to heap
724       profiling:</para>
725
726       <variablelist>
727         <varlistentry>
728           <term>
729             <option>-i<replaceable>secs</replaceable></option>:
730             <indexterm><primary><option>-i</option></primary></indexterm>
731           </term>
732           <listitem>
733             <para>Set the profiling (sampling) interval to
734             <replaceable>secs</replaceable> seconds (the default is
735             0.1&nbsp;second).  Fractions are allowed: for example
736             <option>-i0.2</option> will get 5 samples per second.
737             This only affects heap profiling; time profiles are always
738             sampled on a 1/50 second frequency.</para>
739           </listitem>
740         </varlistentry>
741
742         <varlistentry>
743           <term>
744             <option>-xt</option>
745             <indexterm><primary><option>-xt</option></primary><secondary>RTS option</secondary></indexterm>
746           </term>
747           <listitem>
748             <para>Include the memory occupied by threads in a heap
749             profile.  Each thread takes up a small area for its thread
750             state in addition to the space allocated for its stack
751             (stacks normally start small and then grow as
752             necessary).</para>
753             
754             <para>This includes the main thread, so using
755             <option>-xt</option> is a good way to see how much stack
756             space the program is using.</para>
757
758             <para>Memory occupied by threads and their stacks is
759             labelled as &ldquo;TSO&rdquo; when displaying the profile
760             by closure description or type description.</para>
761           </listitem>
762         </varlistentry>
763
764         <varlistentry>
765           <term>
766             <option>-L<replaceable>num</replaceable></option>
767             <indexterm><primary><option>-L</option></primary><secondary>RTS option</secondary></indexterm>
768           </term>
769           <listitem>
770             <para>
771           Sets the maximum length of a cost-centre stack name in a
772           heap profile. Defaults to 25.
773             </para>
774           </listitem>
775         </varlistentry>
776       </variablelist>
777
778     </sect2>
779     
780     <sect2 id="retainer-prof">
781       <title>Retainer Profiling</title>
782
783       <para>Retainer profiling is designed to help answer questions
784       like <quote>why is this data being retained?</quote>.  We start
785       by defining what we mean by a retainer:</para>
786
787       <blockquote>
788         <para>A retainer is either the system stack, or an unevaluated
789         closure (thunk).</para>
790       </blockquote>
791
792       <para>In particular, constructors are <emphasis>not</emphasis>
793       retainers.</para>
794
795       <para>An object B retains object A if (i) B is a retainer object and
796      (ii) object A can be reached by recursively following pointers
797      starting from object B, but not meeting any other retainer
798      objects on the way. Each live object is retained by one or more
799      retainer objects, collectively called its retainer set, or its
800       <firstterm>retainer set</firstterm>, or its
801       <firstterm>retainers</firstterm>.</para>
802
803       <para>When retainer profiling is requested by giving the program
804       the <option>-hr</option> option, a graph is generated which is
805       broken down by retainer set.  A retainer set is displayed as a
806       set of cost-centre stacks; because this is usually too large to
807       fit on the profile graph, each retainer set is numbered and
808       shown abbreviated on the graph along with its number, and the
809       full list of retainer sets is dumped into the file
810       <filename><replaceable>prog</replaceable>.prof</filename>.</para>
811
812       <para>Retainer profiling requires multiple passes over the live
813       heap in order to discover the full retainer set for each
814       object, which can be quite slow.  So we set a limit on the
815       maximum size of a retainer set, where all retainer sets larger
816       than the maximum retainer set size are replaced by the special
817       set <literal>MANY</literal>.  The maximum set size defaults to 8
818       and can be altered with the <option>-R</option> RTS
819       option:</para>
820       
821       <variablelist>
822         <varlistentry>
823           <term><option>-R</option><replaceable>size</replaceable></term>
824           <listitem>
825             <para>Restrict the number of elements in a retainer set to
826             <replaceable>size</replaceable> (default 8).</para>
827           </listitem>
828         </varlistentry>
829       </variablelist>
830
831       <sect3>
832         <title>Hints for using retainer profiling</title>
833
834         <para>The definition of retainers is designed to reflect a
835         common cause of space leaks: a large structure is retained by
836         an unevaluated computation, and will be released once the
837         computation is forced.  A good example is looking up a value in
838         a finite map, where unless the lookup is forced in a timely
839         manner the unevaluated lookup will cause the whole mapping to
840         be retained.  These kind of space leaks can often be
841         eliminated by forcing the relevant computations to be
842         performed eagerly, using <literal>seq</literal> or strictness
843         annotations on data constructor fields.</para>
844
845         <para>Often a particular data structure is being retained by a
846         chain of unevaluated closures, only the nearest of which will
847         be reported by retainer profiling - for example A retains B, B
848         retains C, and C retains a large structure.  There might be a
849         large number of Bs but only a single A, so A is really the one
850         we're interested in eliminating.  However, retainer profiling
851         will in this case report B as the retainer of the large
852         structure.  To move further up the chain of retainers, we can
853         ask for another retainer profile but this time restrict the
854         profile to B objects, so we get a profile of the retainers of
855         B:</para>
856
857 <screen>
858 <replaceable>prog</replaceable> +RTS -hr -hcB
859 </screen>
860         
861         <para>This trick isn't foolproof, because there might be other
862         B closures in the heap which aren't the retainers we are
863         interested in, but we've found this to be a useful technique
864         in most cases.</para>
865       </sect3>
866     </sect2>
867
868     <sect2 id="biography-prof">
869       <title>Biographical Profiling</title>
870
871       <para>A typical heap object may be in one of the following four
872       states at each point in its lifetime:</para>
873
874       <itemizedlist>
875         <listitem>
876           <para>The <firstterm>lag</firstterm> stage, which is the
877           time between creation and the first use of the
878           object,</para>
879         </listitem>
880         <listitem>
881           <para>the <firstterm>use</firstterm> stage, which lasts from
882           the first use until the last use of the object, and</para>
883         </listitem>
884         <listitem>
885           <para>The <firstterm>drag</firstterm> stage, which lasts
886           from the final use until the last reference to the object
887           is dropped.</para>
888         </listitem>
889         <listitem>
890           <para>An object which is never used is said to be in the
891           <firstterm>void</firstterm> state for its whole
892           lifetime.</para>
893         </listitem>
894       </itemizedlist>
895
896       <para>A biographical heap profile displays the portion of the
897       live heap in each of the four states listed above.  Usually the
898       most interesting states are the void and drag states: live heap
899       in these states is more likely to be wasted space than heap in
900       the lag or use states.</para>
901
902       <para>It is also possible to break down the heap in one or more
903       of these states by a different criteria, by restricting a
904       profile by biography.  For example, to show the portion of the
905       heap in the drag or void state by producer: </para>
906
907 <screen>
908 <replaceable>prog</replaceable> +RTS -hc -hbdrag,void
909 </screen>
910
911       <para>Once you know the producer or the type of the heap in the
912       drag or void states, the next step is usually to find the
913       retainer(s):</para>
914
915 <screen>
916 <replaceable>prog</replaceable> +RTS -hr -hc<replaceable>cc</replaceable>...
917 </screen>
918
919       <para>NOTE: this two stage process is required because GHC
920       cannot currently profile using both biographical and retainer
921       information simultaneously.</para>
922     </sect2>
923
924     <sect2 id="mem-residency">
925       <title>Actual memory residency</title>
926
927       <para>How does the heap residency reported by the heap profiler relate to
928         the actual memory residency of your program when you run it?  You might
929         see a large discrepancy between the residency reported by the heap
930         profiler, and the residency reported by tools on your system
931         (eg. <literal>ps</literal> or <literal>top</literal> on Unix, or the
932         Task Manager on Windows).  There are several reasons for this:</para>
933
934       <itemizedlist>
935         <listitem>
936           <para>There is an overhead of profiling itself, which is subtracted
937             from the residency figures by the profiler.  This overhead goes
938             away when compiling without profiling support, of course.  The
939             space overhead is currently 2 extra
940             words per heap object, which probably results in
941             about a 30% overhead.</para>
942         </listitem>
943
944         <listitem>
945           <para>Garbage collection requires more memory than the actual
946             residency.  The factor depends on the kind of garbage collection
947             algorithm in use:  a major GC in the standard
948             generation copying collector will usually require 3L bytes of
949             memory, where L is the amount of live data.  This is because by
950             default (see the <option>+RTS -F</option> option) we allow the old
951             generation to grow to twice its size (2L) before collecting it, and
952             we require additionally L bytes to copy the live data into.  When
953             using compacting collection (see the <option>+RTS -c</option>
954             option), this is reduced to 2L, and can further be reduced by
955             tweaking the <option>-F</option> option.  Also add the size of the
956             allocation area (currently a fixed 512Kb).</para>
957         </listitem>
958
959         <listitem>
960           <para>The stack isn't counted in the heap profile by default.  See the
961     <option>+RTS -xt</option> option.</para>
962         </listitem>
963
964         <listitem>
965           <para>The program text itself, the C stack, any non-heap data (eg. data
966             allocated by foreign libraries, and data allocated by the RTS), and
967             <literal>mmap()</literal>'d memory are not counted in the heap profile.</para>
968         </listitem>
969       </itemizedlist>
970     </sect2>
971
972   </sect1>
973
974   <sect1 id="hp2ps">
975     <title><command>hp2ps</command>&ndash;&ndash;heap profile to PostScript</title>
976
977     <indexterm><primary><command>hp2ps</command></primary></indexterm>
978     <indexterm><primary>heap profiles</primary></indexterm>
979     <indexterm><primary>postscript, from heap profiles</primary></indexterm>
980     <indexterm><primary><option>-h&lt;break-down&gt;</option></primary></indexterm>
981     
982     <para>Usage:</para>
983     
984 <screen>
985 hp2ps [flags] [&lt;file&gt;[.hp]]
986 </screen>
987
988     <para>The program
989     <command>hp2ps</command><indexterm><primary>hp2ps
990     program</primary></indexterm> converts a heap profile as produced
991     by the <option>-h&lt;break-down&gt;</option> runtime option into a
992     PostScript graph of the heap profile. By convention, the file to
993     be processed by <command>hp2ps</command> has a
994     <filename>.hp</filename> extension. The PostScript output is
995     written to <filename>&lt;file&gt;@.ps</filename>. If
996     <filename>&lt;file&gt;</filename> is omitted entirely, then the
997     program behaves as a filter.</para>
998
999     <para><command>hp2ps</command> is distributed in
1000     <filename>ghc/utils/hp2ps</filename> in a GHC source
1001     distribution. It was originally developed by Dave Wakeling as part
1002     of the HBC/LML heap profiler.</para>
1003
1004     <para>The flags are:</para>
1005
1006     <variablelist>
1007       
1008       <varlistentry>
1009         <term><option>-d</option></term>
1010         <listitem>
1011           <para>In order to make graphs more readable,
1012           <command>hp2ps</command> sorts the shaded bands for each
1013           identifier. The default sort ordering is for the bands with
1014           the largest area to be stacked on top of the smaller ones.
1015           The <option>-d</option> option causes rougher bands (those
1016           representing series of values with the largest standard
1017           deviations) to be stacked on top of smoother ones.</para>
1018         </listitem>
1019       </varlistentry>
1020
1021       <varlistentry>
1022         <term><option>-b</option></term>
1023         <listitem>
1024           <para>Normally, <command>hp2ps</command> puts the title of
1025           the graph in a small box at the top of the page. However, if
1026           the JOB string is too long to fit in a small box (more than
1027           35 characters), then <command>hp2ps</command> will choose to
1028           use a big box instead.  The <option>-b</option> option
1029           forces <command>hp2ps</command> to use a big box.</para>
1030         </listitem>
1031       </varlistentry>
1032
1033       <varlistentry>
1034         <term><option>-e&lt;float&gt;[in&verbar;mm&verbar;pt]</option></term>
1035         <listitem>
1036           <para>Generate encapsulated PostScript suitable for
1037           inclusion in LaTeX documents.  Usually, the PostScript graph
1038           is drawn in landscape mode in an area 9 inches wide by 6
1039           inches high, and <command>hp2ps</command> arranges for this
1040           area to be approximately centred on a sheet of a4 paper.
1041           This format is convenient of studying the graph in detail,
1042           but it is unsuitable for inclusion in LaTeX documents.  The
1043           <option>-e</option> option causes the graph to be drawn in
1044           portrait mode, with float specifying the width in inches,
1045           millimetres or points (the default).  The resulting
1046           PostScript file conforms to the Encapsulated PostScript
1047           (EPS) convention, and it can be included in a LaTeX document
1048           using Rokicki's dvi-to-PostScript converter
1049           <command>dvips</command>.</para>
1050         </listitem>
1051       </varlistentry>
1052
1053       <varlistentry>
1054         <term><option>-g</option></term>
1055         <listitem>
1056           <para>Create output suitable for the <command>gs</command>
1057           PostScript previewer (or similar). In this case the graph is
1058           printed in portrait mode without scaling. The output is
1059           unsuitable for a laser printer.</para>
1060         </listitem>
1061       </varlistentry>
1062
1063       <varlistentry>
1064         <term><option>-l</option></term>
1065         <listitem>
1066           <para>Normally a profile is limited to 20 bands with
1067           additional identifiers being grouped into an
1068           <literal>OTHER</literal> band. The <option>-l</option> flag
1069           removes this 20 band and limit, producing as many bands as
1070           necessary. No key is produced as it won't fit!. It is useful
1071           for creation time profiles with many bands.</para>
1072         </listitem>
1073       </varlistentry>
1074
1075       <varlistentry>
1076         <term><option>-m&lt;int&gt;</option></term>
1077         <listitem>
1078           <para>Normally a profile is limited to 20 bands with
1079           additional identifiers being grouped into an
1080           <literal>OTHER</literal> band. The <option>-m</option> flag
1081           specifies an alternative band limit (the maximum is
1082           20).</para>
1083
1084           <para><option>-m0</option> requests the band limit to be
1085           removed. As many bands as necessary are produced. However no
1086           key is produced as it won't fit! It is useful for displaying
1087           creation time profiles with many bands.</para>
1088         </listitem>
1089       </varlistentry>
1090
1091       <varlistentry>
1092         <term><option>-p</option></term>
1093         <listitem>
1094           <para>Use previous parameters. By default, the PostScript
1095           graph is automatically scaled both horizontally and
1096           vertically so that it fills the page.  However, when
1097           preparing a series of graphs for use in a presentation, it
1098           is often useful to draw a new graph using the same scale,
1099           shading and ordering as a previous one. The
1100           <option>-p</option> flag causes the graph to be drawn using
1101           the parameters determined by a previous run of
1102           <command>hp2ps</command> on <filename>file</filename>. These
1103           are extracted from <filename>file@.aux</filename>.</para>
1104         </listitem>
1105       </varlistentry>
1106
1107       <varlistentry>
1108         <term><option>-s</option></term>
1109         <listitem>
1110           <para>Use a small box for the title.</para>
1111         </listitem>
1112       </varlistentry>
1113       
1114       <varlistentry>
1115         <term><option>-t&lt;float&gt;</option></term>
1116         <listitem>
1117           <para>Normally trace elements which sum to a total of less
1118           than 1&percnt; of the profile are removed from the
1119           profile. The <option>-t</option> option allows this
1120           percentage to be modified (maximum 5&percnt;).</para>
1121
1122           <para><option>-t0</option> requests no trace elements to be
1123           removed from the profile, ensuring that all the data will be
1124           displayed.</para>
1125         </listitem>
1126       </varlistentry>
1127
1128       <varlistentry>
1129         <term><option>-c</option></term>
1130         <listitem>
1131           <para>Generate colour output.</para>
1132         </listitem>
1133       </varlistentry>
1134       
1135       <varlistentry>
1136         <term><option>-y</option></term>
1137         <listitem>
1138           <para>Ignore marks.</para>
1139         </listitem>
1140       </varlistentry>
1141       
1142       <varlistentry>
1143         <term><option>-?</option></term>
1144         <listitem>
1145           <para>Print out usage information.</para>
1146         </listitem>
1147       </varlistentry>
1148     </variablelist>
1149
1150
1151     <sect2 id="manipulating-hp">
1152       <title>Manipulating the hp file</title>
1153
1154 <para>(Notes kindly offered by Jan-Willhem Maessen.)</para>
1155
1156 <para>
1157 The <filename>FOO.hp</filename> file produced when you ask for the
1158 heap profile of a program <filename>FOO</filename> is a text file with a particularly
1159 simple structure. Here's a representative example, with much of the
1160 actual data omitted:
1161 <screen>
1162 JOB "FOO -hC"
1163 DATE "Thu Dec 26 18:17 2002"
1164 SAMPLE_UNIT "seconds"
1165 VALUE_UNIT "bytes"
1166 BEGIN_SAMPLE 0.00
1167 END_SAMPLE 0.00
1168 BEGIN_SAMPLE 15.07
1169   ... sample data ...
1170 END_SAMPLE 15.07
1171 BEGIN_SAMPLE 30.23
1172   ... sample data ...
1173 END_SAMPLE 30.23
1174 ... etc.
1175 BEGIN_SAMPLE 11695.47
1176 END_SAMPLE 11695.47
1177 </screen>
1178 The first four lines (<literal>JOB</literal>, <literal>DATE</literal>, <literal>SAMPLE_UNIT</literal>, <literal>VALUE_UNIT</literal>) form a
1179 header.  Each block of lines starting with <literal>BEGIN_SAMPLE</literal> and ending
1180 with <literal>END_SAMPLE</literal> forms a single sample (you can think of this as a
1181 vertical slice of your heap profile).  The hp2ps utility should accept
1182 any input with a properly-formatted header followed by a series of
1183 *complete* samples.
1184 </para>
1185 </sect2>
1186
1187     <sect2>
1188       <title>Zooming in on regions of your profile</title>
1189
1190 <para>
1191 You can look at particular regions of your profile simply by loading a
1192 copy of the <filename>.hp</filename> file into a text editor and deleting the unwanted
1193 samples.  The resulting <filename>.hp</filename> file can be run through <command>hp2ps</command> and viewed
1194 or printed.
1195 </para>
1196 </sect2>
1197
1198     <sect2>
1199       <title>Viewing the heap profile of a running program</title>
1200
1201 <para>
1202 The <filename>.hp</filename> file is generated incrementally as your
1203 program runs.  In principle, running <command>hp2ps</command> on the incomplete file
1204 should produce a snapshot of your program's heap usage.  However, the
1205 last sample in the file may be incomplete, causing <command>hp2ps</command> to fail.  If
1206 you are using a machine with UNIX utilities installed, it's not too
1207 hard to work around this problem (though the resulting command line
1208 looks rather Byzantine):
1209 <screen>
1210   head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \
1211     | hp2ps > FOO.ps
1212 </screen>
1213
1214 The command <command>fgrep -n END_SAMPLE FOO.hp</command> finds the
1215 end of every complete sample in <filename>FOO.hp</filename>, and labels each sample with
1216 its ending line number.  We then select the line number of the last
1217 complete sample using <command>tail</command> and <command>cut</command>.  This is used as a
1218 parameter to <command>head</command>; the result is as if we deleted the final
1219 incomplete sample from <filename>FOO.hp</filename>.  This results in a properly-formatted
1220 .hp file which we feed directly to <command>hp2ps</command>.
1221 </para>
1222 </sect2>
1223     <sect2>
1224       <title>Viewing a heap profile in real time</title>
1225
1226 <para>
1227 The <command>gv</command> and <command>ghostview</command> programs
1228 have a "watch file" option can be used to view an up-to-date heap
1229 profile of your program as it runs.  Simply generate an incremental
1230 heap profile as described in the previous section.  Run <command>gv</command> on your
1231 profile:
1232 <screen>
1233   gv -watch -seascape FOO.ps 
1234 </screen>
1235 If you forget the <literal>-watch</literal> flag you can still select
1236 "Watch file" from the "State" menu.  Now each time you generate a new
1237 profile <filename>FOO.ps</filename> the view will update automatically.
1238 </para>
1239
1240 <para>
1241 This can all be encapsulated in a little script:
1242 <screen>
1243   #!/bin/sh
1244   head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \
1245     | hp2ps > FOO.ps
1246   gv -watch -seascape FOO.ps &amp;
1247   while [ 1 ] ; do
1248     sleep 10 # We generate a new profile every 10 seconds.
1249     head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \
1250       | hp2ps > FOO.ps
1251   done
1252 </screen>
1253 Occasionally <command>gv</command> will choke as it tries to read an incomplete copy of
1254 <filename>FOO.ps</filename> (because <command>hp2ps</command> is still running as an update
1255 occurs).  A slightly more complicated script works around this
1256 problem, by using the fact that sending a SIGHUP to gv will cause it
1257 to re-read its input file:
1258 <screen>
1259   #!/bin/sh
1260   head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \
1261     | hp2ps > FOO.ps
1262   gv FOO.ps &amp;
1263   gvpsnum=$!
1264   while [ 1 ] ; do
1265     sleep 10
1266     head -`fgrep -n END_SAMPLE FOO.hp | tail -1 | cut -d : -f 1` FOO.hp \
1267       | hp2ps > FOO.ps
1268     kill -HUP $gvpsnum
1269   done    
1270 </screen>
1271 </para>
1272 </sect2>
1273   </sect1>
1274
1275   <sect1 id="hpc">
1276     <title>Observing Code Coverage</title>
1277     <indexterm><primary>code coverage</primary></indexterm>
1278     <indexterm><primary>Haskell Program Coverage</primary></indexterm>
1279     <indexterm><primary>hpc</primary></indexterm>
1280
1281     <para>
1282       Code coverage tools allow a programmer to determine what parts of
1283       their code have been actually executed, and which parts have
1284       never actually been invoked.  GHC has an option for generating
1285       instrumented code that records code coverage as part of the
1286       <ulink url="http://www.haskell.org/hpc">Haskell Program Coverage
1287       </ulink>(HPC) toolkit, which is included with GHC. HPC tools can
1288       be used to render the generated code coverage information into
1289       human understandable format.  </para>
1290
1291     <para>
1292       Correctly instrumented code provides coverage information of two
1293       kinds: source coverage and boolean-control coverage. Source
1294       coverage is the extent to which every part of the program was
1295       used, measured at three different levels: declarations (both
1296       top-level and local), alternatives (among several equations or
1297       case branches) and expressions (at every level).  Boolean
1298       coverage is the extent to which each of the values True and
1299       False is obtained in every syntactic boolean context (ie. guard,
1300       condition, qualifier).  </para>
1301
1302     <para>
1303       HPC displays both kinds of information in two primary ways:
1304       textual reports with summary statistics (hpc report) and sources
1305       with color mark-up (hpc markup).  For boolean coverage, there
1306       are four possible outcomes for each guard, condition or
1307       qualifier: both True and False values occur; only True; only
1308       False; never evaluated. In hpc-markup output, highlighting with
1309       a yellow background indicates a part of the program that was
1310       never evaluated; a green background indicates an always-True
1311       expression and a red background indicates an always-False one.
1312     </para> 
1313
1314    <sect2><title>A small example: Reciprocation</title>
1315
1316     <para>
1317      For an example we have a program, called Recip.hs, which computes exact decimal
1318      representations of reciprocals, with recurring parts indicated in
1319      brackets.
1320     </para>
1321 <programlisting>
1322 reciprocal :: Int -> (String, Int)
1323 reciprocal n | n > 1 = ('0' : '.' : digits, recur)
1324              | otherwise = error
1325                   "attempting to compute reciprocal of number &lt;= 1"
1326   where
1327   (digits, recur) = divide n 1 []
1328 divide :: Int -> Int -> [Int] -> (String, Int)
1329 divide n c cs | c `elem` cs = ([], position c cs)
1330               | r == 0      = (show q, 0)
1331               | r /= 0      = (show q ++ digits, recur)
1332   where
1333   (q, r) = (c*10) `quotRem` n
1334   (digits, recur) = divide n r (c:cs)
1335
1336 position :: Int -> [Int] -> Int
1337 position n (x:xs) | n==x      = 1
1338                   | otherwise = 1 + position n xs
1339
1340 showRecip :: Int -> String
1341 showRecip n =
1342   "1/" ++ show n ++ " = " ++
1343   if r==0 then d else take p d ++ "(" ++ drop p d ++ ")"
1344   where
1345   p = length d - r
1346   (d, r) = reciprocal n
1347
1348 main = do
1349   number &lt;- readLn
1350   putStrLn (showRecip number)
1351   main
1352 </programlisting>
1353
1354     <para>The HPC instrumentation is enabled using the -fhpc flag.
1355     </para>
1356
1357 <screen>
1358 $ ghc -fhpc Recip.hs --make 
1359 </screen>
1360     <para>HPC index (.mix) files are placed placed in .hpc subdirectory. These can be considered like
1361     the .hi files for HPC. 
1362    </para>
1363 <screen>
1364 $ ./Recip
1365 1/3
1366 = 0.(3)
1367 </screen>
1368     <para>We can generate a textual summary of coverage:</para>
1369 <screen>
1370 $ hpc report Recip
1371  80% expressions used (81/101)
1372  12% boolean coverage (1/8)
1373       14% guards (1/7), 3 always True, 
1374                         1 always False, 
1375                         2 unevaluated
1376        0% 'if' conditions (0/1), 1 always False
1377      100% qualifiers (0/0)
1378  55% alternatives used (5/9)
1379 100% local declarations used (9/9)
1380 100% top-level declarations used (5/5)
1381 </screen>
1382     <para>We can also generate a marked-up version of the source.</para>
1383 <screen>
1384 $ hpc markup Recip
1385 writing Recip.hs.html
1386 </screen>
1387     <para>
1388                 This generates one file per Haskell module, and 4 index files,
1389                 hpc_index.html, hpc_index_alt.html, hpc_index_exp.html,
1390                 hpc_index_fun.html.
1391         </para>
1392      </sect2> 
1393
1394      <sect2><title>Options for instrumenting code for coverage</title>
1395         <para>
1396                 Turning on code coverage is easy, use the -fhpc flag. 
1397                 Instrumented and non-instrumented can be freely mixed.
1398                 When compiling the Main module GHC automatically detects when there
1399                 is an hpc compiled file, and adds the correct initialization code.
1400         </para>
1401
1402      </sect2>
1403
1404      <sect2><title>The hpc toolkit</title>
1405
1406       <para>
1407       The hpc toolkit uses a cvs/svn/darcs-like interface, where a
1408       single binary contains many function units.</para> 
1409 <screen>
1410 $ hpc 
1411 Usage: hpc COMMAND ...
1412
1413 Commands:
1414   help        Display help for hpc or a single command
1415 Reporting Coverage:
1416   report      Output textual report about program coverage
1417   markup      Markup Haskell source with program coverage
1418 Processing Coverage files:
1419   sum         Sum multiple .tix files in a single .tix file
1420   combine     Combine two .tix files in a single .tix file
1421   map         Map a function over a single .tix file
1422 Coverage Overlays:
1423   overlay     Generate a .tix file from an overlay file
1424   draft       Generate draft overlay that provides 100% coverage
1425 Others:
1426   show        Show .tix file in readable, verbose format
1427   version     Display version for hpc
1428 </screen>
1429
1430      <para>In general, these options act on .tix file after an
1431      instrumented binary has generated it, which hpc acting as a
1432      conduit between the raw .tix file, and the more detailed reports
1433      produced. 
1434         </para>
1435           
1436         <para>
1437                 The hpc tool assumes you are in the top-level directory of
1438                 the location where you built your application, and the .tix
1439                 file is in the same top-level directory. You can use the
1440                 flag --srcdir to use hpc for any other directory, and use
1441                 --srcdir multiple times to analyse programs compiled from
1442                 difference locations, as is typical for packages.
1443         </para>
1444           
1445         <para>
1446         We now explain in more details the major modes of hpc.
1447      </para>
1448
1449        <sect3><title>hpc report</title>
1450                 <para>hpc report gives a textual report of coverage. By default,
1451                         all modules and packages are considered in generating report,
1452                         unless include or exclude are used. The report is a summary
1453                         unless the --per-module flag is used. The --xml-output option
1454                         allows for tools to use hpc to glean coverage. 
1455                 </para> 
1456 <screen>
1457 $ hpc help report
1458 Usage: hpc report [OPTION] .. &lt;TIX_FILE&gt; [&lt;MODULE&gt; [&lt;MODULE&gt; ..]]
1459
1460 Options:
1461
1462     --per-module                  show module level detail
1463     --decl-list                   show unused decls
1464     --exclude=[PACKAGE:][MODULE]  exclude MODULE and/or PACKAGE
1465     --include=[PACKAGE:][MODULE]  include MODULE and/or PACKAGE
1466     --srcdir=DIR                  path to source directory of .hs files
1467                                   multi-use of srcdir possible
1468     --hpcdir=DIR                  sub-directory that contains .mix files
1469                                   default .hpc [rarely used]
1470     --xml-output                  show output in XML
1471 </screen>
1472        </sect3>
1473        <sect3><title>hpc markup</title>
1474                 <para>hpc markup marks up source files into colored html.
1475                 </para>
1476 <screen>
1477 $ hpc help markup
1478 Usage: hpc markup [OPTION] .. &lt;TIX_FILE&gt; [&lt;MODULE&gt; [&lt;MODULE&gt; ..]]
1479
1480 Options:
1481
1482     --exclude=[PACKAGE:][MODULE]  exclude MODULE and/or PACKAGE
1483     --include=[PACKAGE:][MODULE]  include MODULE and/or PACKAGE
1484     --srcdir=DIR                  path to source directory of .hs files
1485                                   multi-use of srcdir possible
1486     --hpcdir=DIR                  sub-directory that contains .mix files
1487                                   default .hpc [rarely used]
1488     --fun-entry-count             show top-level function entry counts
1489     --highlight-covered           highlight covered code, rather that code gaps
1490     --destdir=DIR                 path to write output to
1491 </screen>
1492
1493        </sect3>
1494        <sect3><title>hpc sum</title>
1495                 <para>hpc sum adds together any number of .tix files into a single 
1496                 .tix file. hpc sum does not change the original .tix file; it generates a new .tix file. 
1497                 </para>
1498 <screen>
1499 $ hpc help sum
1500 Usage: hpc sum [OPTION] .. &lt;TIX_FILE&gt; [&lt;TIX_FILE&gt; [&lt;TIX_FILE&gt; ..]]
1501 Sum multiple .tix files in a single .tix file
1502
1503 Options:
1504
1505     --exclude=[PACKAGE:][MODULE]  exclude MODULE and/or PACKAGE
1506     --include=[PACKAGE:][MODULE]  include MODULE and/or PACKAGE
1507     --output=FILE                 output FILE
1508     --union                       use the union of the module namespace (default is intersection)
1509 </screen>
1510        </sect3>
1511        <sect3><title>hpc combine</title>
1512                 <para>hpc combine is the swiss army knife of hpc. It can be 
1513                  used to take the difference between .tix files, to subtract one
1514                 .tix file from another, or to add two .tix files. hpc combine does not
1515                 change the original .tix file; it generates a new .tix file. 
1516                 </para>
1517 <screen>
1518 $ hpc help combine
1519 Usage: hpc combine [OPTION] .. &lt;TIX_FILE&gt; &lt;TIX_FILE&gt;
1520 Combine two .tix files in a single .tix file
1521
1522 Options:
1523
1524     --exclude=[PACKAGE:][MODULE]  exclude MODULE and/or PACKAGE
1525     --include=[PACKAGE:][MODULE]  include MODULE and/or PACKAGE
1526     --output=FILE                 output FILE
1527     --function=FUNCTION           combine .tix files with join function, default = ADD
1528                                   FUNCTION = ADD | DIFF | SUB
1529     --union                       use the union of the module namespace (default is intersection)
1530 </screen>
1531        </sect3>
1532        <sect3><title>hpc map</title>
1533                 <para>hpc map inverts or zeros a .tix file. hpc map does not
1534                 change the original .tix file; it generates a new .tix file. 
1535                 </para>
1536 <screen>
1537 $ hpc help map
1538 Usage: hpc map [OPTION] .. &lt;TIX_FILE&gt; 
1539 Map a function over a single .tix file
1540
1541 Options:
1542
1543     --exclude=[PACKAGE:][MODULE]  exclude MODULE and/or PACKAGE
1544     --include=[PACKAGE:][MODULE]  include MODULE and/or PACKAGE
1545     --output=FILE                 output FILE
1546     --function=FUNCTION           apply function to .tix files, default = ID
1547                                   FUNCTION = ID | INV | ZERO
1548     --union                       use the union of the module namespace (default is intersection)
1549 </screen>
1550        </sect3>
1551        <sect3><title>hpc overlay and hpc draft</title>
1552                 <para>
1553                         Overlays are an experimental feature of HPC, a textual description
1554                         of coverage. hpc draft is used to generate a draft overlay from a .tix file,
1555                         and hpc overlay generates a .tix files from an overlay.
1556                 </para>
1557 <screen>
1558 % hpc help overlay
1559 Usage: hpc overlay [OPTION] .. &lt;OVERLAY_FILE&gt; [&lt;OVERLAY_FILE&gt; [...]]
1560
1561 Options:
1562
1563     --srcdir=DIR   path to source directory of .hs files
1564                    multi-use of srcdir possible
1565     --hpcdir=DIR   sub-directory that contains .mix files
1566                    default .hpc [rarely used]
1567     --output=FILE  output FILE
1568 % hpc help draft  
1569 Usage: hpc draft [OPTION] .. &lt;TIX_FILE&gt;
1570
1571 Options:
1572
1573     --exclude=[PACKAGE:][MODULE]  exclude MODULE and/or PACKAGE
1574     --include=[PACKAGE:][MODULE]  include MODULE and/or PACKAGE
1575     --srcdir=DIR                  path to source directory of .hs files
1576                                   multi-use of srcdir possible
1577     --hpcdir=DIR                  sub-directory that contains .mix files
1578                                   default .hpc [rarely used]
1579     --output=FILE                 output FILE
1580 </screen>
1581       </sect3>
1582      </sect2>
1583      <sect2><title>Caveats and Shortcomings of Haskell Program Coverage</title>
1584           <para>
1585                 HPC does not attempt to lock the .tix file, so multiple concurrently running
1586                 binaries in the same directory will exhibit a race condition. There is no way
1587                 to change the name of the .tix file generated, apart from renaming the binary.
1588                 HPC does not work with GHCi.
1589           </para>
1590     </sect2>
1591   </sect1>
1592
1593   <sect1 id="ticky-ticky">
1594     <title>Using &ldquo;ticky-ticky&rdquo; profiling (for implementors)</title>
1595     <indexterm><primary>ticky-ticky profiling</primary></indexterm>
1596
1597     <para>(ToDo: document properly.)</para>
1598
1599     <para>It is possible to compile Haskell programs so that
1600     they will count lots and lots of interesting things, e.g., number
1601     of updates, number of data constructors entered, etc., etc.  We
1602     call this &ldquo;ticky-ticky&rdquo;
1603     profiling,<indexterm><primary>ticky-ticky
1604     profiling</primary></indexterm> <indexterm><primary>profiling,
1605     ticky-ticky</primary></indexterm> because that's the sound a CPU
1606     makes when it is running up all those counters
1607     (<emphasis>slowly</emphasis>).</para>
1608
1609     <para>Ticky-ticky profiling is mainly intended for implementors;
1610     it is quite separate from the main &ldquo;cost-centre&rdquo;
1611     profiling system, intended for all users everywhere.</para>
1612
1613     <para>
1614       You don't need to build GHC, the libraries, or the RTS a special
1615       way in order to use ticky-ticky profiling.  You can decide on a
1616       module-by-module basis which parts of a program have the
1617       counters compiled in, using the
1618       compile-time <option>-ticky</option> option.  Those modules that
1619       were not compiled with <option>-ticky</option> won't contribute
1620       to the ticky-ticky profiling results, and that will normally
1621       include all the pre-compiled packages that your program links
1622       with.
1623     </para>
1624
1625     <para>
1626       To get your compiled program to spit out the ticky-ticky
1627       numbers:
1628
1629       <itemizedlist>
1630         <listitem>
1631           <para>
1632             Link the program with <option>-debug</option>
1633             (<option>-ticky</option> is a synonym
1634             for <option>-debug</option> at link-time).  This links in
1635             the debug version of the RTS, which includes the code for
1636             aggregating and reporting the results of ticky-ticky
1637             profilng.
1638           </para>
1639         </listitem>
1640         <listitem>
1641           <para>
1642             Run the program with the <option>-r</option> RTS
1643             option<indexterm><primary>-r RTS option</primary></indexterm>.
1644             See <xref linkend="runtime-control"/>.
1645           </para>
1646         </listitem>
1647       </itemizedlist>
1648     </para>
1649
1650     <para>
1651       Here is a sample ticky-ticky statistics file, generated by
1652       the invocation
1653       <command>foo +RTS -rfoo.ticky</command>.
1654       </para>
1655     
1656 <screen>
1657  foo +RTS -rfoo.ticky
1658
1659 ALLOCATIONS: 3964631 (11330900 words total: 3999476 admin, 6098829 goods, 1232595 slop)
1660                                 total words:        2     3     4     5    6+
1661   69647 (  1.8%) function values                 50.0  50.0   0.0   0.0   0.0
1662 2382937 ( 60.1%) thunks                           0.0  83.9  16.1   0.0   0.0
1663 1477218 ( 37.3%) data values                     66.8  33.2   0.0   0.0   0.0
1664       0 (  0.0%) big tuples
1665       2 (  0.0%) black holes                      0.0 100.0   0.0   0.0   0.0
1666       0 (  0.0%) prim things
1667   34825 (  0.9%) partial applications             0.0   0.0   0.0 100.0   0.0
1668       2 (  0.0%) thread state objects             0.0   0.0   0.0   0.0 100.0
1669
1670 Total storage-manager allocations: 3647137 (11882004 words)
1671         [551104 words lost to speculative heap-checks]
1672
1673 STACK USAGE:
1674
1675 ENTERS: 9400092  of which 2005772 (21.3%) direct to the entry code
1676                   [the rest indirected via Node's info ptr]
1677 1860318 ( 19.8%) thunks
1678 3733184 ( 39.7%) data values
1679 3149544 ( 33.5%) function values
1680                   [of which 1999880 (63.5%) bypassed arg-satisfaction chk]
1681  348140 (  3.7%) partial applications
1682  308906 (  3.3%) normal indirections
1683       0 (  0.0%) permanent indirections
1684
1685 RETURNS: 5870443
1686 2137257 ( 36.4%) from entering a new constructor
1687                   [the rest from entering an existing constructor]
1688 2349219 ( 40.0%) vectored [the rest unvectored]
1689
1690 RET_NEW:         2137257:  32.5% 46.2% 21.3%  0.0%  0.0%  0.0%  0.0%  0.0%  0.0%
1691 RET_OLD:         3733184:   2.8% 67.9% 29.3%  0.0%  0.0%  0.0%  0.0%  0.0%  0.0%
1692 RET_UNBOXED_TUP:       2:   0.0%  0.0%100.0%  0.0%  0.0%  0.0%  0.0%  0.0%  0.0%
1693
1694 RET_VEC_RETURN : 2349219:   0.0%  0.0%100.0%  0.0%  0.0%  0.0%  0.0%  0.0%  0.0%
1695
1696 UPDATE FRAMES: 2241725 (0 omitted from thunks)
1697 SEQ FRAMES:    1
1698 CATCH FRAMES:  1
1699 UPDATES: 2241725
1700       0 (  0.0%) data values
1701   34827 (  1.6%) partial applications
1702                   [2 in place, 34825 allocated new space]
1703 2206898 ( 98.4%) updates to existing heap objects (46 by squeezing)
1704 UPD_CON_IN_NEW:         0:       0      0      0      0      0      0      0      0      0
1705 UPD_PAP_IN_NEW:     34825:       0      0      0  34825      0      0      0      0      0
1706
1707 NEW GEN UPDATES: 2274700 ( 99.9%)
1708
1709 OLD GEN UPDATES: 1852 (  0.1%)
1710
1711 Total bytes copied during GC: 190096
1712
1713 **************************************************
1714 3647137 ALLOC_HEAP_ctr
1715 11882004 ALLOC_HEAP_tot
1716   69647 ALLOC_FUN_ctr
1717   69647 ALLOC_FUN_adm
1718   69644 ALLOC_FUN_gds
1719   34819 ALLOC_FUN_slp
1720   34831 ALLOC_FUN_hst_0
1721   34816 ALLOC_FUN_hst_1
1722       0 ALLOC_FUN_hst_2
1723       0 ALLOC_FUN_hst_3
1724       0 ALLOC_FUN_hst_4
1725 2382937 ALLOC_UP_THK_ctr
1726       0 ALLOC_SE_THK_ctr
1727  308906 ENT_IND_ctr
1728       0 E!NT_PERM_IND_ctr requires +RTS -Z
1729 [... lots more info omitted ...]
1730       0 GC_SEL_ABANDONED_ctr
1731       0 GC_SEL_MINOR_ctr
1732       0 GC_SEL_MAJOR_ctr
1733       0 GC_FAILED_PROMOTION_ctr
1734   47524 GC_WORDS_COPIED_ctr
1735 </screen>
1736
1737     <para>The formatting of the information above the row of asterisks
1738     is subject to change, but hopefully provides a useful
1739     human-readable summary.  Below the asterisks <emphasis>all
1740     counters</emphasis> maintained by the ticky-ticky system are
1741     dumped, in a format intended to be machine-readable: zero or more
1742     spaces, an integer, a space, the counter name, and a newline.</para>
1743
1744     <para>In fact, not <emphasis>all</emphasis> counters are
1745     necessarily dumped; compile- or run-time flags can render certain
1746     counters invalid.  In this case, either the counter will simply
1747     not appear, or it will appear with a modified counter name,
1748     possibly along with an explanation for the omission (notice
1749     <literal>ENT&lowbar;PERM&lowbar;IND&lowbar;ctr</literal> appears
1750     with an inserted <literal>!</literal> above).  Software analysing
1751     this output should always check that it has the counters it
1752     expects.  Also, beware: some of the counters can have
1753     <emphasis>large</emphasis> values!</para>
1754
1755   </sect1>
1756
1757 </chapter>
1758
1759 <!-- Emacs stuff:
1760      ;;; Local Variables: ***
1761      ;;; mode: xml ***
1762      ;;; sgml-parent-document: ("users_guide.xml" "book" "chapter") ***
1763      ;;; End: ***
1764  -->