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