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