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