<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- %% -->
<!-- %W  debug.msk                 GAP manual                    Thomas Breuer -->
<!-- %W                                                       Alexander Hulpke -->
<!-- %W                                                       Martin Schönert -->
<!-- %% -->
<!-- %H  @(#)<M>Id: debug.msk,v 1.26 2006/03/07 22:05:56 jjm Exp </M> -->
<!-- %% -->

<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Chapter Label="Debugging and Profiling Facilities">
<Heading>Debugging and Profiling Facilities</Heading>

This chapter describes some functions that are useful mainly for
debugging and profiling purposes.
<P/>
Probably the most important debugging tool in &GAP; is the break loop
(see Section <Ref Sect="Break Loops"/>) which can be entered by putting
an <Ref Func="Error"/> statement into your code or by hitting Control-C.
In the break loop one can inspect variables, stack traces and issue 
commands as usual in an interactive &GAP; session. See also the
<Ref Func="DownEnv"/>, <Ref Func="UpEnv"/>, <Ref Func="Where"/> and
<Ref Func="WhereWithVars"/>
functions.
<P/>
Sections&nbsp;<Ref Sect="sect:ApplicableMethod"/>
and&nbsp;<Ref Sect="Tracing Methods"/> show how to get
information about the methods chosen by the method selection mechanism
(see chapter&nbsp;<Ref Chap="Method Selection"/>).
<P/>
The final sections describe functions for collecting statistics about
computations (see <Ref Func="Runtime"/>, <Ref Sect="Profiling"/>).


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Recovery from NoMethodFound-Errors">
<Heading>Recovery from NoMethodFound-Errors</Heading>

When the method selection fails because there is no applicable method, an
error as in the following example occurs and a break loop is entered:
<P/>
<Log><![CDATA[
gap> IsNormal(2,2);
Error, no method found! For debugging hints type ?Recovery from NoMethodFound
Error, no 1st choice method found for `IsNormal' on 2 arguments at GAPROOT/lib/methsel2.g:250 called from
<function "HANDLE_METHOD_NOT_FOUND">( <arguments> )
 called from read-eval loop at *stdin*:1
type 'quit;' to quit to outer loop
brk> 
]]></Log>
<P/>
This only says, that the method selection tried to find a method for 
<C>IsNormal</C> on two arguments and failed. In this situation it is
crucial to find out, why this happened. Therefore there are a few functions
which can display further information.
Note that you can leave the break loop by the <K>quit</K> command
(see&nbsp;<Ref Subsect="quit"/>)
and that the information about the incident is no longer accessible
afterwards.
<P/>
<!-- %If you use <K>return</K> you have to supply a method -->
<!-- %which matches. -->
<#Include Label="ShowArguments">
<#Include Label="ShowArgument">
<#Include Label="ShowDetails">
<#Include Label="ShowMethods">
<#Include Label="ShowOtherMethods">

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="sect:ApplicableMethod">
<Heading>Inspecting Applicable Methods</Heading>

<#Include Label="ApplicableMethod">

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Tracing Methods">
<Heading>Tracing Methods</Heading>

<#Include Label="TraceMethods">
<#Include Label="TraceAllMethods">
<#Include Label="UntraceMethods">
<#Include Label="UntraceAllMethods">
<#Include Label="TraceImmediateMethods">

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Info Functions">
<Heading>Info Functions</Heading>

The <Index>verbosity of GAP output</Index><Ref Func="Info"/> mechanism
permits operations to display intermediate results or
information about the progress of the algorithms.
Information is always given according to one or more <E>info classes</E>. Each of the
info classes defined in the &GAP; library usually covers a certain range
of algorithms, so for example <C>InfoLattice</C> covers all the cyclic extension
algorithms for the computation of a subgroup lattice.
<P/>

Note that not all info classes defined in the &GAP; library are currently
documented.  Many &GAP; packages define additional info classes, which are
typically documented in the corresponding package documentation.
The function <Ref Func="ShowUsedInfoClasses"/> will show all info classes which
&GAP; considers while executing code.
<P/>
The amount of information to be displayed by each info class can be separately
specified by the user. This is done by selecting a non-negative integer
<E>level</E> for the info class: no information will be displayed at level 0,
and the higher the level, the more information that will be displayed. At
creation, an info class has level 0. By default, all built-in GAP info classes
have level 0, except for the following info classes, which have level 1:
<List>
  <Item><Ref InfoClass="InfoWarning"/>,</Item>
  <Item><Ref InfoClass="InfoPackageLoading"/>,</Item>
  <Item><C>InfoDebug</C>,</Item>
  <Item><C>InfoPerformance</C>,</Item>
  <Item><C>InfoTempDirectories</C>,</Item>
  <Item><C>InfoPrimeInt</C>, and</Item>
  <Item><C>InfoSLP</C>.</Item>
</List>
<P/>
<ManSection>
<Oper Name="NewInfoClass" Arg='name'/>

<Description>
creates a new info class with name <A>name</A>.
</Description>
</ManSection>
<P/>
<ManSection>
<Func Name="DeclareInfoClass" Arg='name'/>

<Description>
creates a new info class with name <A>name</A> and binds it to the global
variable <A>name</A>. The variable must previously be writable, and is made 
readonly by this function.
</Description>
</ManSection>
<P/>
<ManSection>
<Oper Name="SetInfoLevel" Arg='infoclass, level'/>

<Description>
  Sets the info level for <A>infoclass</A> to the non-negative integer
  <A>level</A>.
</Description>
</ManSection>
<P/>
<ManSection>
<Oper Name="InfoLevel" Arg='infoclass'/>

<Description>
returns the info level of <A>infoclass</A>.
</Description>
</ManSection>
<P/>
<ManSection>
<Func Name="ShowUsedInfoClasses" Arg='infoclass'/>

<Description>
Called with argument <K>true</K>, this makes &GAP; print the info class and level of
 any executed <Ref Func="Info"/> statement. Calling with the argument <K>false</K> stops this
 printing.

Each level of each info class is only printed once. The history of printed
info classes and levels is reset whenever <K>true</K> is passed.
<P/>

<Example><![CDATA[
gap> ShowUsedInfoClasses(true);
gap> Intersection(Group((1,3,2,4,5,6)), Group((1,2,3,4,5,6)));
#I Would print info with SetInfoLevel(InfoOptions,1)
#I Would print info with SetInfoLevel(InfoBckt,1)
#I Would print info with SetInfoLevel(InfoBckt,3)
#I Would print info with SetInfoLevel(InfoBckt,5)
Group(())
gap> Intersection(Group((1,3,2,4,5,6)), Group((1,2,3,4,5,6)));
Group(())
gap> ShowUsedInfoClasses(false);
]]></Example>

</Description>
</ManSection>
<P/>

<ManSection>
<Func Name="Info" Arg='infoclass, level, info[, moreinfo ...]'/>

<Description>
If the info level of <A>infoclass</A> is at least <A>level</A>, then the remaining
arguments, <A>info</A>, and possibly <A>moreinfo</A> and so on, are evaluated.
(Technically, <Ref Func="Info"/> is a keyword and not a function.)
<P/>
By default, the results of these evaluations are
viewed, preceded by the string <C>"#I  "</C> and followed by a newline.
<P/>
If the info level of <A>infoclass</A> is strictly less than <A>level</A>, then
the third and subsequent arguments are not evaluated.
(The latter can save substantial time when displaying difficult results.)
<P/>
The behaviour can be customized with <Ref Func="SetInfoHandler"/>.
<P/>
<Example><![CDATA[
gap> InfoExample:=NewInfoClass("InfoExample");;
gap> Info(InfoExample,1,"one");Info(InfoExample,2,"two");
gap> SetInfoLevel(InfoExample,1);
gap> Info(InfoExample,1,"one");Info(InfoExample,2,"two");
#I  one
gap> SetInfoLevel(InfoExample,2);
gap> Info(InfoExample,1,"one");Info(InfoExample,2,"two");
#I  one
#I  two
gap> InfoLevel(InfoExample);
2
gap> Info(InfoExample,3,Length(Combinations([1..9999])));
]]></Example>
<P/>
Note that the last <Ref Func="Info"/> call is executed without problems,
since the actual level <C>2</C> of <C>InfoExample</C> causes <Ref Func="Info"/> to ignore
the last argument, which prevents <C>Length(Combinations([1..9999]))</C>
from being evaluated;
note that an evaluation would be impossible due to memory restrictions.
<P/>

A set of info classes (called an <E>info selector</E>) may be passed to a
single <Ref Func="Info"/> statement. As a shorthand, info classes and selectors
may be combined with <C>+</C> rather than <Ref Func="Union" Label="for a list"/>.
In this case, the
message is triggered if the level of <E>any</E> of the classes is high enough.
<P/>
<Example><![CDATA[
gap> InfoExample:=NewInfoClass("InfoExample");;
gap> SetInfoLevel(InfoExample,0);
gap> Info(InfoExample + InfoWarning, 1, "hello");
#I  hello
gap> Info(InfoExample + InfoWarning, 2, "hello");
gap> SetInfoLevel(InfoExample,2);
gap> Info(InfoExample + InfoWarning, 2, "hello");
#I  hello
gap> InfoLevel(InfoWarning);
1
]]></Example>
</Description>
</ManSection>

<ManSection>
<Heading>Customizing <Ref Func="Info"/> statements</Heading>
<Func Arg="infoclass, handler" Name="SetInfoHandler" />
<Func Arg="infoclass, out" Name="SetInfoOutput" />
<Func Arg="infoclass" Name="UnbindInfoOutput" />
<Func Arg="infoclass" Name="InfoOutput" />
<Func Arg="out" Name="SetDefaultInfoOutput" />
<Returns>nothing</Returns>
<Description>
This allows one to customize what happens in an
<C>Info(<A>infoclass</A>, <A>level</A>, ...)</C> statement.<P/> 
In the first function, <A>handler</A>
must be a function with three arguments <A>infoclass</A>, <A>level</A>,
<A>list</A>. Here <A>list</A> is the list containing the third argument and
any subsequent optional arguments of the <Ref Func="Info"/> call.
<P/>
The default handler is the function <C>DefaultInfoHandler</C>.
<Index Key="DefaultInfoHandler"><C>DefaultInfoHandler</C></Index>
It prints <C>"#I  "</C>, then the third and further arguments of 
the info statement, and finally a <C>"\n"</C>.
<P/>
If the first argument of an <Ref Func="Info"/> statement is a sum of
Info classes, the handler of the first summand is used.
<P/>
The file or stream to which <Ref Func="Info"/> statements for individual
<Ref Func="Info"/> classes print can be overriden with
<Ref Func="SetInfoOutput"/>, retrieved with <Ref Func="InfoOutput"/>
and reset to the default with <Ref Func="UnbindInfoOutput"/>.
The initial default for all <Ref Func="Info"/>
classes is the string <C>"*Print*"</C> which means the current output
file. The default can be changed with <Ref Func="SetDefaultInfoOutput"/>.  
The argument <A>out</A> can be a filename or an open stream, 
the special names <C>"*Print*"</C>, <C>"*errout*</C> and <C>"*stdout*</C>
are also recognized.<P/>
For example,
<C>SetDefaultInfoOutput("*errout*");</C> would send <Ref Func="Info"/> 
output to standard error, which can be interesting if &GAP;s output is
redirected.
</Description>
</ManSection>

<ManSection>
<InfoClass Name="InfoWarning"/>

<Description>
is an info class to which general warnings are sent at level 1,
which is its default level.
More specialised warnings are shown via calls of <Ref Func="Info"/> at
<Ref InfoClass="InfoWarning"/> level 2,
e.g.&nbsp;information about the autoloading of &GAP; packages and the
initial line matched when displaying an on-line help topic.
</Description>
</ManSection>

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Assertions">
<Heading>Assertions</Heading>

Assertions are used to find errors in algorithms.
They test whether intermediate results conform to required conditions
and issue an error if not.
<P/>
<ManSection>
<Func Name="SetAssertionLevel" Arg='lev'/>

<Description>
assigns the global assertion level to <A>lev</A>. By default it is zero.
</Description>
</ManSection>
<P/>
<ManSection>
<Func Name="AssertionLevel" Arg=''/>

<Description>
returns the current assertion level.
</Description>
</ManSection>
<P/>
<ManSection>
<Func Name="Assert" Arg='lev, cond[, message]'/>

<Description>
With two arguments, if the global assertion level is at least <A>lev</A>,
condition <A>cond</A> is tested and if it does not return <K>true</K> an
error is raised.
Thus <C>Assert(lev, <A>cond</A>)</C> is equivalent to the code
<Log><![CDATA[
if AssertionLevel() >= lev and not <cond> then
  Error("Assertion failure");
fi;
]]></Log>
<P/>
With the <A>message</A> argument form of the <Ref Func="Assert"/> statement,
if the global assertion level is at least <A>lev</A>, condition <A>cond</A>
is tested and if it does not return <K>true</K> then <A>message</A> is
evaluated and printed.
<P/>
Assertions are used at various places in the library.
Thus turning assertions on can slow code execution significantly.
</Description>
</ManSection>

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Timing">
<Heading>Timing</Heading>

<ManSection>
<Func Name="Runtimes" Arg=''/>

<Description>
<Ref Func="Runtimes"/> returns a record with components bound to integers
or <K>fail</K>. 
Each integer is the cpu time (processor time) in milliseconds spent by &GAP;
in a certain status:
<P/>
<List>
<Mark><C>user_time</C></Mark>
<Item>
   cpu time spent with &GAP; functions (without child processes).
</Item>
<Mark><C>system_time</C></Mark>
<Item>
   cpu time spent in system calls, e.g., file access 
   (<K>fail</K> if not available).
</Item>
<Mark><C>user_time_children</C></Mark>
<Item>
   cpu time spent in child processes (<K>fail</K> if not available).
</Item>
<Mark><C>system_time_children</C></Mark>
<Item>
   cpu time spent in system calls by child processes
   (<K>fail</K> if not available).
</Item>
</List>
<P/>
Note that this function is not fully supported on all systems. Only the
<C>user_time</C> component is (and may on some systems include the system
time). 
<P/>
The following example demonstrates tasks which contribute to the different
time components:
<P/>
<Log><![CDATA[
gap> Runtimes(); # after startup
rec( user_time := 3980, system_time := 60, user_time_children := 0, 
  system_time_children := 0 )
gap> Exec("cat /usr/bin/*||wc"); # child process with a lot of file access
 893799 7551659 200928302
gap> Runtimes();
rec( user_time := 3990, system_time := 60, user_time_children := 1590, 
  system_time_children := 600 )
gap> a:=0;;for i in [1..100000000] do a:=a+1; od; # GAP user time
gap> Runtimes();  
rec( user_time := 12980, system_time := 70, user_time_children := 1590, 
  system_time_children := 600 )
gap> ?blabla  # first call of help, a lot of file access
Help: no matching entry found
gap> Runtimes();
rec( user_time := 13500, system_time := 440, user_time_children := 1590, 
  system_time_children := 600 )
]]></Log>
</Description>
</ManSection>


<ManSection>
<Func Name="Runtime" Arg=''/>

<Description>
<Ref Func="Runtime"/> returns the time spent by &GAP;
in milliseconds as an integer.
It is the same as the value of the <C>user_time</C> component given by
<Ref Func="Runtimes"/>, as explained above.
<P/>
See <Ref Func="StringTime"/> for a translation from milliseconds into
hour/minute format.
</Description>
</ManSection>



<ManSection>
<Func Name="NanosecondsSinceEpoch" Arg=''/>
<Func Name="NanosecondsSinceEpochInfo" Arg=''/>
<Description>
<Ref Func="NanosecondsSinceEpoch"/> returns the time in nanoseconds
that has passed since some fixed, but unspecified time in the past.

This function is appropriate for doing wallclock time measurements.

The actual resolution depends on the system that &GAP; is run on.
Information about the used timers can be obtained by calling
<Ref Func="NanosecondsSinceEpochInfo"/>, which returns a record
containing members <C>Method</C>, <C>Monotonic</C>, <C>Reliable</C>
and <C>Resolution</C>.

<P/>
<C>Method</C> is a string describing the method used to obtain timer
values. This will usually contain the name of the syscall used.
<P/>
<C>Monotonic</C> is a boolean. If it is <K>true</K>, then the values
returned by <Ref Func="NanosecondsSinceEpoch"/> are guaranteed to be
strictly monotonically increasing between two calls, if it is <K>false</K>
then there is no such guarantee.
<P/>
<C>Resolution</C> is an integer reflecting the resolution of the timer
used in nanoseconds.
<P/>
<C>Reliable</C> is a boolean. If it is <K>true</K> then the
value <C>Resolution</C> is deemed reliable in the sense that it was
obtained by querying the operating system, otherwise <C>Resolution</C>
should be treated as an estimate.
</Description>
</ManSection>

<ManSection>
  <Var Name="time"/>

<Description>
In the read-eval-print loop,
<Ref Var="time"/> stores the number of milliseconds the last command
took (see also <Ref Var="memory_allocated"/> for the number of bytes of
memory it allocated).
</Description>
</ManSection>

<ManSection>
<Func Name="Sleep" Arg='time'/>
<Func Name="MicroSleep" Arg='time'/>

<Description>
These functions make GAP stop execution for a given period of time. The time
to stop is given to <Ref Func="Sleep"/> in seconds and <Ref Func="MicroSleep"/>
in microseconds.
</Description>
</ManSection>

</Section>

<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Tracking Memory Usage">
  <Heading>Tracking Memory Usage</Heading>

  <ManSection>
    <Func Name="TotalMemoryAllocated" Arg=""/>
    <Description> <Ref Func="TotalMemoryAllocated"/> returns the total amount of memory
    in bytes allocated by the &GAP; memory manager since &GAP; started.
    </Description>
  </ManSection>
  
  <ManSection>
    <Var Name="memory_allocated"/>
    <Description> In the read-eval-print loop, <Ref Var="memory_allocated"/>
    stores the number of bytes of memory allocated by the last completed statement
    (see also <Ref Var="time"/> for the number of milliseconds it took).
  </Description>
  </ManSection>

</Section>

<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Profiling">
<Heading>Profiling</Heading>

Profiling of code can be used to determine in which parts of a program
how much time has been spent and how much memory has been allocated
during runtime.

GAP has two different methods of profiling. GAP can either profile by
function, or line-by-line. Line by line profiling is currently only
used for code coverage, while function profiling tracks memory and time
usage.

<Subsection Label="FunctionProfiling">
<Heading>Function Profiling</Heading>

This section describes how to profiling at the function level.
The idea is that
<List>
<Item>
    first one switches on profiling for those &GAP; functions
    the performance of which one wants to check,
</Item>
<Item>
    then one runs some &GAP; computations,
</Item>
<Item>
    then one looks at the profile information collected during these
    computations,
</Item>
<Item>
    then one runs more computations (perhaps clearing all profile information
    before, see <Ref Func="ClearProfile"/>),
</Item>
<Item>
    and finally one switches off profiling.
</Item>
</List>
<P/>
For switching on and off profiling, &GAP; supports entering a list of
functions
(see <Ref Func="ProfileFunctions"/>, <Ref Func="UnprofileFunctions"/>)
or a list of operations whose methods shall be (un)profiled
(<Ref Func="ProfileMethods"/>, <Ref Func="UnprofileMethods"/>),
and <Ref Func="DisplayProfile"/> can be used to show profile information
about functions in a given list.
<P/>
Besides these functions, <Ref Func="ProfileGlobalFunctions"/>,
<Ref Func="ProfileOperations"/>, and
<Ref Func="ProfileOperationsAndMethods"/> can be used for switching on
or off profiling for <E>all</E> global functions, operations, and operations
together with all their methods, respectively,
and for showing profile information about these functions.
<P/>
Note that &GAP; will perform more slowly when profiling than when not.
</Subsection>
<#Include Label="ProfileGlobalFunctions">
<#Include Label="ProfileOperations">
<#Include Label="ProfileOperationsAndMethods">

<#Include Label="ProfileFunctions">
<#Include Label="UnprofileFunctions">
<#Include Label="ProfileMethods">
<#Include Label="UnprofileMethods">

<#Include Label="DisplayProfile">
<#Include Label="ClearProfile">

<!-- The source of the following subsection is not stored in lib/profile.g
     because the GAP output has to be adjusted from time to time,
     and this is easier if there is no indentation. -->
<Subsection Label="subsect:profiling_example">
<Heading>An Example of Function Profiling</Heading>

Let us suppose we want to get information about the computation of the
conjugacy classes of a certain permutation group.
For that,
first we create the group,
then we start profiling for all global functions and for all operations
and their methods,
then we compute the conjugacy classes,
and then we stop profiling.
<P/>
<Log><![CDATA[
gap> g:= PrimitiveGroup( 24, 1 );;
gap> ProfileGlobalFunctions( true );
gap> ProfileOperationsAndMethods( true );
gap> ConjugacyClasses( g );;
gap> ProfileGlobalFunctions( false );
gap> ProfileOperationsAndMethods( false );
]]></Log>
<P/>
Now the profile information is available.
We can list the information for all profiled functions with
<Ref Func="DisplayProfile"/>.
<P/>
<Log><![CDATA[
gap> DisplayProfile();
  count  self/ms  chld/ms  stor/kb  chld/kb  package  function              
  17647        0        0      275        0  GAP      BasePoint             
  10230        0        0      226        0  (oprt.)  ShallowCopy           
  10139        0        0        0        0           PositionSortedOp: for*
  10001        0        0      688        0           UniteSet: for two int*
  10001        8        0       28      688  (oprt.)  UniteSet              
  14751       12        0        0        0           =: for two families: *
  10830        8        4      182      276  GAP      Concatenation         
   2700       20       12      313       55  GAP      AddRefinement         
   2444       28        4     3924      317  GAP      ConjugateStabChain    
   4368        0       32        7      714  (oprt.)  Size                  
   2174       32        4     1030      116  GAP      List                  
    585        4       32       45      742  GAP      RRefine               
   1532       32        8      194       56  GAP      AddGeneratorsExtendSc*
   1221        8       32      349      420  GAP      Partition             
 185309       28       12        0        0  (oprt.)  Length                
    336        4       40       95      817  GAP      ExtendSeriesPermGroup 
      4       28       20      488      454  (oprt.)  Sortex                
   2798        0       52       54      944  GAP      StabChainForcePoint   
    560        4       48       83      628  GAP      StabChainSwap         
    432       16       40      259      461  GAP      SubmagmaWithInversesNC
 185553       48        8      915       94  (oprt.)  Add                   
     26        0       64        0     2023  (oprt.)  CentralizerOp         
     26        0       64        0     2023  GAP      CentralizerOp: perm g*
     26        0       64        0     2023  GAP      Centralizer: try to e*
    152        4       64        0     2024  (oprt.)  Centralizer           
   1605        0       68        0     2032  (oprt.)  StabilizerOfExternalS*
     26        0       68        0     2024  GAP      Meth(StabilizerOfExte*
    382        0       96       69     1922  GAP      TryPcgsPermGroup      
   5130        4       96      309     3165  GAP      ForAll                
   7980       24      116      330     6434  GAP      ChangeStabChain       
  12076       12      136      351     6478  GAP      ProcessFixpoint       
    192        0      148        4     3029  GAP      StabChainMutable: cal*
   2208        4      148        3     3083  (oprt.)  StabChainMutable      
    217        0      160        0     3177  (oprt.)  StabChainOp           
    217       12      148       60     3117  GAP      StabChainOp: group an*
    216       36      464      334    12546  GAP      PartitionBacktrack    
   1479       12      668      566    18474  GAP      RepOpElmTuplesPermGro*
   1453       12      684       56    18460  GAP      in: perm class rep    
    126        0      728       13    19233  GAP      ConjugacyClassesTry   
      1        0      736        0    19671  GAP      ConjugacyClassesByRan*
      2        0      736        2    19678  (oprt.)  ConjugacyClasses      
      1        0      736        0    19675  GAP      ConjugacyClasses: per*
  13400     1164        0        0        0  (oprt.)  Position              
             484             12052                    OTHER                 
            2048             23319                    TOTAL                 
]]></Log>
<P/>
We can restrict the list to global functions with
<Ref Func="ProfileGlobalFunctions"/>.
<P/>
<Log><![CDATA[
gap> ProfileGlobalFunctions();
  count  self/ms  chld/ms  stor/kb  chld/kb  package  function              
  17647        0        0      275        0  GAP      BasePoint             
  10830        8        4      182      276  GAP      Concatenation         
   2700       20       12      313       55  GAP      AddRefinement         
   2444       28        4     3924      317  GAP      ConjugateStabChain    
   2174       32        4     1030      116  GAP      List                  
    585        4       32       45      742  GAP      RRefine               
   1532       32        8      194       56  GAP      AddGeneratorsExtendSc*
   1221        8       32      349      420  GAP      Partition             
    336        4       40       95      817  GAP      ExtendSeriesPermGroup 
   2798        0       52       54      944  GAP      StabChainForcePoint   
    560        4       48       83      628  GAP      StabChainSwap         
    432       16       40      259      461  GAP      SubmagmaWithInversesNC
    382        0       96       69     1922  GAP      TryPcgsPermGroup      
   5130        4       96      309     3165  GAP      ForAll                
   7980       24      116      330     6434  GAP      ChangeStabChain       
  12076       12      136      351     6478  GAP      ProcessFixpoint       
    216       36      464      334    12546  GAP      PartitionBacktrack    
   1479       12      668      566    18474  GAP      RepOpElmTuplesPermGro*
    126        0      728       13    19233  GAP      ConjugacyClassesTry   
      1        0      736        0    19671  GAP      ConjugacyClassesByRan*
            1804             14536                    OTHER                 
            2048             23319                    TOTAL                 
]]></Log>
<P/>
We can restrict the list to operations with
<Ref Func="ProfileOperations"/>.
<P/>
<Log><![CDATA[
gap> ProfileOperations();
  count  self/ms  chld/ms  stor/kb  chld/kb  package  function              
  10230        0        0      226        0  (oprt.)  ShallowCopy           
  10001        8        0       28      688  (oprt.)  UniteSet              
   4368        0       32        7      714  (oprt.)  Size                  
 185309       28       12        0        0  (oprt.)  Length                
      4       28       20      488      454  (oprt.)  Sortex                
 185553       48        8      915       94  (oprt.)  Add                   
     26        0       64        0     2023  (oprt.)  CentralizerOp         
    152        4       64        0     2024  (oprt.)  Centralizer           
   1605        0       68        0     2032  (oprt.)  StabilizerOfExternalS*
   2208        4      148        3     3083  (oprt.)  StabChainMutable      
    217        0      160        0     3177  (oprt.)  StabChainOp           
      2        0      736        2    19678  (oprt.)  ConjugacyClasses      
  13400     1164        0        0        0  (oprt.)  Position              
             764             21646                    OTHER                 
            2048             23319                    TOTAL                 
]]></Log>
<P/>
We can restrict the list to operations and their methods with
<Ref Func="ProfileOperationsAndMethods"/>.
<P/>
<Log><![CDATA[
gap> ProfileOperationsAndMethods();
  count  self/ms  chld/ms  stor/kb  chld/kb  package  function              
  10230        0        0      226        0  (oprt.)  ShallowCopy           
  10139        0        0        0        0           PositionSortedOp: for*
  10001        0        0      688        0           UniteSet: for two int*
  10001        8        0       28      688  (oprt.)  UniteSet              
  14751       12        0        0        0           =: for two families: *
   4368        0       32        7      714  (oprt.)  Size                  
 185309       28       12        0        0  (oprt.)  Length                
      4       28       20      488      454  (oprt.)  Sortex                
 185553       48        8      915       94  (oprt.)  Add                   
     26        0       64        0     2023  (oprt.)  CentralizerOp         
     26        0       64        0     2023  GAP      CentralizerOp: perm g*
     26        0       64        0     2023  GAP      Centralizer: try to e*
    152        4       64        0     2024  (oprt.)  Centralizer           
   1605        0       68        0     2032  (oprt.)  StabilizerOfExternalS*
     26        0       68        0     2024  GAP      Meth(StabilizerOfExte*
    192        0      148        4     3029  GAP      StabChainMutable: cal*
   2208        4      148        3     3083  (oprt.)  StabChainMutable      
    217        0      160        0     3177  (oprt.)  StabChainOp           
    217       12      148       60     3117  GAP      StabChainOp: group an*
   1453       12      684       56    18460  GAP      in: perm class rep    
      2        0      736        2    19678  (oprt.)  ConjugacyClasses      
      1        0      736        0    19675  GAP      ConjugacyClasses: per*
  13400     1164        0        0        0  (oprt.)  Position              
             728             20834                    OTHER                 
            2048             23319                    TOTAL                 
]]></Log>
<P/>
Finally, we can restrict the list to explicitly given functions with
<Ref Func="DisplayProfile"/>,
by entering the list of functions as an argument.
<P/>
<Log><![CDATA[
gap> DisplayProfile( [ StabChainOp, Centralizer ] );
  count  self/ms  chld/ms  stor/kb  chld/kb  package  function              
    152        4       64        0     2024  (oprt.)  Centralizer           
    217        0      160        0     3177  (oprt.)  StabChainOp           
            2044             23319                    OTHER                 
            2048             23319                    TOTAL                 
]]></Log>

<!-- extend this example by changing the thresholds, and call ClearProfile -->

</Subsection>
<Subsection Label="linebylineprofiling">
<Heading>Line By Line Profiling</Heading>
Line By Line profiling tracks which lines have been executed in a piece
of GAP code. Built into GAP are the methods necessary to generate profiles,
the resulting profiles can be displayed with the 'profiling' package.
</Subsection> 

<Subsection Label="subsect:linebylineprofexample">
<Heading>Line by Line profiling example</Heading>
There are two kinds of profiles GAP can build:

<List>
  <Item> Coverage : This records which lines of code are executed</Item>
  <Item> Timing : This records how much time is spend executing each line of code </Item>
</List>

A timing profile provides more information, but will take longer to generate
and parse.

A timing profile is generated using the functions <Ref Func="ProfileLineByLine"/>
and <Ref Func="UnprofileLineByLine"/>, as follows:

<Log><![CDATA[
gap> ProfileLineByLine("output.gz");
gap> Size(AlternatingGroup(10)); ; # Execute some GAP code you want to profile
gap> UnprofileLineByLine();
]]></Log>

For code coverage, use instead the functions <Ref Func="CoverageLineByLine"/>
and <Ref Func="UncoverageLineByLine"/>.

The profiler will only record lines which are read and executed while
the profiler is running. If you want to perform code coverage or profile
GAP's library, then you can use the GAP command  line option '--cover filename.gz',
which executes  <Ref Func="CoverageLineByLine"/> before GAP starts. Similarly
the option '--prof filename.gz' executes <Ref Func="ProfileLineByLine"/> before
GAP starts.


The profiler is designed for high performance, because of this, there are some
limitations which users should be aware of:

<List>
  <Item> By default the profiler records the wall-clock time which has passed,
    rather than the CPU time taken (because it is lower overhead), so any time
    taken writing commands will be charged to the last GAP statement which was
    executed. Therefore it is better to write a function which starts profiling,
    executes your code, and then stops profiling.
  </Item>
  <Item>
    If you end the filename with ".gz", the resulting file will automatically
    be compressed. This is highly recommended!
  </Item>
  <Item>
    The profiler can only track GAP code which occurs in a function -- this
    is most obvious when looking at code coverage examples, which will appear
    to miss lines of code in files not in a function.
  </Item>
  <Item>
    If the current GAP is forked, using the <C>IO_fork</C> function in the
    <Package>IO</Package> package,
    a new profile output file will be created for the new child process, with
    the process ID of the child attached to the end of the filename.
  </Item>
</List>

Profiles are transformed into a human-readable form with
'profiling' package, for example with the 'OutputAnnotatedCodeCoverageFiles' function.

</Subsection>

<#Include Label="ProfileLineByLine">
<#Include Label="CoverageLineByLine">
<#Include Label="UnprofileLineByLine">
<#Include Label="UncoverageLineByLine">
<#Include Label="ActivateProfileColour">
<#Include Label="IsLineByLineProfileActive">


<#Include Label="DisplayCacheStats">
<#Include Label="ClearCacheStats">

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Information about the version used">
<Heading>Information about the version used</Heading>

<Index Key="GAPInfo.Version"><C>GAPInfo.Version</C></Index>

The global variable <C>GAPInfo.Version</C> (see <Ref Var="GAPInfo"/>)
contains the version number of the version of &GAP;. Its value can be 
checked other version number using <Ref Func="CompareVersionNumbers"/>.
<P/>
To produce sample citations for the used version of &GAP; or for a 
package available in this &GAP; installation, use <Ref Func="Cite"/>.
<P/>
If you wish to report a problem to &GAP; Support or &GAP; Forum, it may
be useful to not only report the version used, but also to include the 
&GAP; banner displays the information about the architecture for which 
the &GAP; binary is built, used libraries and loaded packages.
</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Test Files">
<Heading>Test Files</Heading>

Test files are used to check that &GAP; produces correct results in
certain computations. A selection of test files for the library can be
found in the <F>tst</F> directory of the &GAP; distribution.

<#Include Label="StartStopTest">

<#Include Label="[1]{testinstall.g}">

<Log><![CDATA[
test file         time(msec)
-------------------------------------------
testing: ................/gap4r5/tst/zlattice.tst
zlattice.tst               0
testing: ................/gap4r5/tst/gaussian.tst
gaussian.tst              10
[ further lines deleted ]
]]></Log>

<#Include Label="[1]{teststandard.g}">
<P/>

<#Include Label="Test">
<#Include Label="TestDirectory">

See also <Ref Func="TestPackage"/> for the information on running standard
tests for &GAP; packages.
</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Debugging Recursion">
<Heading>Debugging Recursion</Heading>

The &GAP; interpreter monitors the level of nesting of &GAP;
functions during execution.
By default, whenever this nesting reaches a multiple of <M>5000</M>,
&GAP; enters a break loop (<Ref Sect="Break Loops"/>) allowing you
to terminate the calculation, or enter <B>Return</B><C>;</C> to continue it. 
<P/>
<Log><![CDATA[
gap> dive:= function(depth) if depth>1 then dive(depth-1); fi; return; end;
function( depth ) ... end
gap> dive(100);
gap> OnBreak:= function() Where(1); end; # shorter traceback
function(  ) ... end
gap> dive(6000);
recursion depth trap (5000)
 at
dive( depth - 1 );
 called from
dive( depth - 1 ); called from
...
Entering break read-eval-print loop ...
you can 'quit;' to quit to outer loop, or
you may 'return;' to continue
brk> return;
gap> dive(11000);
recursion depth trap (5000)
 at
dive( depth - 1 );
 called from
dive( depth - 1 ); called from
...
Entering break read-eval-print loop ...
you can 'quit;' to quit to outer loop, or
you may 'return;' to continue
brk> return;
recursion depth trap (10000)
 at
dive( depth - 1 );
 called from
dive( depth - 1 ); called from
...
Entering break read-eval-print loop ...
you can 'quit;' to quit to outer loop, or
you may 'return;' to continue
brk> return;
gap> 
]]></Log>
<P/>

This behaviour can be controlled using the following procedures.

<ManSection>
<Func Name="SetRecursionTrapInterval" Arg='interval'/>
<Func Name="GetRecursionDepth" Arg=''/>

<Description>
<Ref Func="GetRecursionDepth"/> returns the nesting level of the GAP
interpreter. This is reset to 0 every time the break loop is entered.
<Ref Func="SetRecursionTrapInterval"/> sets the depth of the stack at which
GAP will enter the Break loop. <A>interval</A> must be a non-negative small
integer (between 0 and <M>2^{28}</M>).
An <A>interval</A> of 0 suppresses the monitoring of recursion
altogether. In this case excessive recursion may cause &GAP; to crash.
<P/>
<Log><![CDATA[
gap> GetRecursionDepth();
0
gap> dive := function(depth)
>  if depth>1 then
>    dive(depth-1);
>  else
>    Print("Depth ", GetRecursionDepth());
>  fi;
> end;;
gap> SetRecursionTrapInterval(1000);
gap> dive(100);
Depth 100
gap> dive(2500);
recursion depth trap (1000)
 at
dive( depth - 1 );
 called from
dive( depth - 1 ); called from
...
Entering break read-eval-print loop ...
you can 'quit;' to quit to outer loop, or
you may 'return;' to continue
brk> return;
recursion depth trap (2000)
 at
dive( depth - 1 );
 called from
dive( depth - 1 ); called from
...
Entering break read-eval-print loop ...
you can 'quit;' to quit to outer loop, or
you may 'return;' to continue
brk> GetRecursionDepth();
0
brk> return;
gap> SetRecursionTrapInterval(-1);
SetRecursionTrapInterval( <interval> ): <interval> must be a non-negative smal\
l integer
not in any function
Entering break read-eval-print loop ...
you can 'quit;' to quit to outer loop, or
you can replace <interval> via 'return <interval>;' to continue
brk> return 0;
gap> dive(20000);
Depth 20000
gap> dive(2000000);
Segmentation fault
]]></Log>
</Description>


</ManSection>

</Section>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<Section Label="Global Memory Information">
<Heading>Global Memory Information</Heading>

<Index Key="GASMAN"><C>GASMAN</C></Index>

The &GAP; environment provides automatic memory management, so that
the programmer does not need to concern themselves with allocating
space for objects, or recovering space when objects are no longer
needed. The component of the kernel which provides this is called
<C>GASMAN</C> (&GAP; Storage MANager).  Messages reporting garbage
collections performed by <C>GASMAN</C> can be switched on
by the <C>-g</C> command
line option (see section <Ref Sect="Command Line Options"/>).
There are also some
facilities to access information from <C>GASMAN</C> from &GAP; programs.

<#Include Label="GasmanStatistics">
<#Include Label="GasmanMessageStatus">
<#Include Label="GasmanLimits">

</Section>
</Chapter>


<!-- %%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% -->
<!-- %% -->
<!-- %E -->
