Debugging
*********

Octave includes a built-in debugger to aid in the development of scripts.  This can be used to interrupt the execution of an Octave script at a certain point, or when certain conditions are met.  Once execution has stopped, and debug mode is entered, the symbol table at the point where execution has stopped can be examined and modified to check for errors.

The normal command-line editing and history functions are available in debug mode.

Entering Debug Mode
===================

There are two basic means of interrupting the execution of an Octave script.  These are breakpoints (see Breakpoints), discussed in the next section, and interruption based on some condition.

Octave supports three means to stop execution based on the values set in the functions debug_on_interrupt, debug_on_warning, and debug_on_error.

 -- VAL =: debug_on_interrupt ()
 -- OLD_VAL =: debug_on_interrupt (NEW_VAL)
 -- OLD_VAL =: debug_on_interrupt (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave will try to enter debugging mode when it receives an interrupt signal (typically generated with C-c).

     If a second interrupt signal is received before reaching the debugging mode, a normal interrupt will occur.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. debug_on_error, debug_on_warning

 -- VAL =: debug_on_warning ()
 -- OLD_VAL =: debug_on_warning (NEW_VAL)
 -- OLD_VAL =: debug_on_warning (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave will try to enter the debugger when a warning is encountered.

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. debug_on_error, debug_on_interrupt

 -- VAL =: debug_on_error ()
 -- OLD_VAL =: debug_on_error (NEW_VAL)
 -- OLD_VAL =: debug_on_error (NEW_VAL, "local")
     Query or set the internal variable that controls whether Octave will try to enter the debugger when an error is encountered.

     This will also inhibit printing of the normal traceback message (you will only see the top-level error message).

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function. debug_on_warning, debug_on_interrupt

Leaving Debug Mode
==================

Use either dbcont or return to leave the debug mode and continue the normal execution of the script.

 -- dbcont:
     Leave command-line debugging mode and continue code execution normally. dbstep, dbquit

To quit debug mode and return directly to the prompt without executing any additional code use dbquit.

 -- dbquit:
 -- dbquit: all
     Quit debugging mode immediately without further code execution.

     With no arguments, exit the current debugging level.  With argument all, exit all debugging levels and return to the Octave prompt. dbcont, dbstep

Finally, typing exit or quit at the debug prompt will result in Octave terminating normally.

Breakpoints
===========

Breakpoints can be set in any m-file function by using the dbstop function.

 -- dbstop: FCN
 -- dbstop: FCN LINE
 -- dbstop: FCN LINE1 LINE2 ...
 -- dbstop: LINE1 ...
 -- dbstop: in FCN
 -- dbstop: in FCN at LINE
 -- dbstop: in FCN at LINE if "CONDITION"
 -- dbstop: in CLASS at METHOD
 -- dbstop: if EVENT
 -- dbstop: if EVENT ID
 -- dbstop: (BP_STRUCT)
 -- RLINE =: dbstop ...

     Set breakpoints for the built-in debugger.

     FCN is the name of a function on the current path.  When already in debug mode the FCN argument can be omitted and the current function will be used.  Breakpoints at subfunctions are set with the scope operator >.  For example, If file.m has a subfunction fcn2, then a breakpoint in fcn2 can be specified by file>fcn2.

     LINE is the line number at which to break.  If LINE is not specified, it defaults to the first executable line in the file fcn.m.  Multiple lines can be specified in a single command; when function syntax is used, the lines may also be passed as a single vector argument ([LINE1, LINE2, ...]).

     CONDITION is any Octave expression that can be evaluated in the code context that exists at the breakpoint.  When the breakpoint is encountered, CONDITION will be evaluated, and execution will stop if CONDITION is true.  If CONDITION cannot be evaluated, for example because it refers to an undefined variable, an error will be thrown. Expressions with side effects (such as y++ > 1) will alter variables, and should generally be avoided.  Conditions containing quotes (", ') or comment characters (#, %) must be enclosed in quotes.  (This does not apply to conditions entered from the editor's context menu.)  For example:

          dbstop in axis at 246 if 'any (opt == "x")'

     The form specifying EVENT does not cause a specific breakpoint at a given function and line number.  Instead it causes debug mode to be entered when certain unexpected events are encountered.  Possible values are

     error
          Stop when an error is reported.  This is equivalent to specifying both debug_on_error (true) and debug_on_interrupt (true).

     caught error
          Stop when an error is caught by a try-catch block (not yet implemented).

     interrupt
          Stop when an interrupt (Ctrl-C) occurs.

     naninf
          Stop when code returns a non-finite value (not yet implemented).

     warning
          Stop when a warning is reported.  This is equivalent to specifying debug_on_warning (true).

     The events error, caught error, and warning can all be followed by a string specifying an error ID or warning ID.  If that is done, only errors with the specified ID will cause execution to stop.  To stop on one of a set of IDs, multiple dbstop commands must be issued.

     Breakpoints and events can be removed using the dbclear command with the same syntax.

     It is possible to save all breakpoints and restore them at once by issuing the commands bp_state = dbstatus; ...; dbstop (bp_state).

     The optional output RLINE is the real line number where the breakpoint was set.  This can differ from the specified line if the line is not executable.  For example, if a breakpoint attempted on a blank line then Octave will set the real breakpoint at the next executable line.

     When a file is re-parsed, such as when it is modified outside the GUI, all breakpoints within the file are cleared.

     dbclear, dbstatus, dbstep, debug_on_error, debug_on_warning, debug_on_interrupt

Breakpoints in class methods are also supported (e.g., dbstop ("@class/method")).  However, breakpoints cannot be set in built-in functions (e.g., sin, etc.) or dynamically loaded functions (i.e., oct-files).

To set a breakpoint immediately upon entering a function use line number 1, or omit the line number entirely and just give the function name.  When setting the breakpoint Octave will ignore the leading comment block, and the breakpoint will be set on the first executable statement in the function.  For example:

     dbstop ("asind", 1)
     => 29

Note that the return value of 29 means that the breakpoint was effectively set to line 29.  The status of breakpoints in a function can be queried with dbstatus.

 -- dbstatus:
 -- dbstatus: FCN
 -- BP_LIST =: dbstatus ...
     Report the location of active breakpoints.

     When called with no input or output arguments, print the list of all functions with breakpoints and the line numbers where those breakpoints are set.

     If a function name FCN is specified then only report breakpoints for the named function and its subfunctions.

     The optional return argument BP_LIST is a struct array with the following fields:

     name
          The name of the function with a breakpoint.  A subfunction, say fcn2 within an m-file, say file.m, is specified as file>fcn2.

     file
          The name of the m-file where the function code is located.

     line
          The line number with the breakpoint.

     cond
          The condition that must be satisfied for the breakpoint to be active, or the empty string for unconditional breakpoints.

     If dbstop if error is true but no explicit IDs are specified, the return value will have an empty field called "errs".  If IDs are specified, the errs field will have one row per ID.  If dbstop if error is false, there is no "errs" field. The "warn" field is set similarly by dbstop if warning.

     dbstop, dbclear, dbwhere, dblist, dbstack

Reusing the previous example, dbstatus ("asind") will return 29.  The breakpoints listed can then be cleared with the dbclear function.

 -- dbclear: FCN
 -- dbclear: FCN LINE
 -- dbclear: FCN LINE1 LINE2 ...
 -- dbclear: LINE ...
 -- dbclear: all
 -- dbclear: in FCN
 -- dbclear: in FCN at LINE
 -- dbclear: if EVENT
 -- dbclear: ("FCN")
 -- dbclear: ("FCN", LINE)
 -- dbclear: ("FCN", LINE1, LINE2, ...)
 -- dbclear: ("FCN", LINE1, ...)
 -- dbclear: (LINE, ...)
 -- dbclear: ("all")
     Delete a breakpoint at line number LINE in the function FCN.

     Arguments are

     fcn
          Function name as a string variable.  When already in debug mode this argument can be omitted and the current function will be used.

     line
          Line number from which to remove a breakpoint.  Multiple lines may be given as separate arguments or as a vector.

     event
          An event such as error, interrupt, or warning (see dbstop for details).

     When called without a line number specification all breakpoints in the named function are cleared.

     If the requested line is not a breakpoint no action is performed.

     The special keyword "all" will clear all breakpoints from all files. dbstop, dbstatus, dbwhere

A breakpoint may also be set in a subfunction.  For example, if a file contains the functions

     function y = func1 (x)
       y = func2 (x);
     endfunction
     function y = func2 (x)
       y = x + 1;
     endfunction

then a breakpoint can be set at the start of the subfunction directly with

     dbstop func1>func2
     => 5

Note that > is the character that distinguishes subfunctions from the m-file containing them.

Another simple way of setting a breakpoint in an Octave script is the use of the keyboard function.

 -- keyboard: ()
 -- keyboard: ("PROMPT")
     Stop m-file execution and enter debug mode.

     When the keyboard function is executed, Octave prints a prompt and waits for user input.  The input strings are then evaluated and the results are printed.  This makes it possible to examine the values of variables within a function, and to assign new values if necessary.  To leave the prompt and return to normal execution type return or dbcont. The keyboard function does not return an exit status.

     If keyboard is invoked without arguments, a default prompt of debug>  is used. dbstop, dbcont, dbquit

The keyboard function is placed in a script at the point where the user desires that the execution be stopped.  It automatically sets the running script into the debug mode.

Debug Mode
==========

There are three additional support functions that allow the user to find out where in the execution of a script Octave entered the debug mode, and to print the code in the script surrounding the point where Octave entered debug mode.

 -- dbwhere:
     In debugging mode, report the current file and line number where execution is stopped. dbstack, dblist, dbstatus, dbcont, dbstep, dbup, dbdown

 -- dbtype:
 -- dbtype: LINENO
 -- dbtype: STARTL:ENDL
 -- dbtype: STARTL:end
 -- dbtype: FCN
 -- dbtype: FCN LINENO
 -- dbtype: FCN STARTL:ENDL
 -- dbtype: FCN STARTL:end
     Display a script file with line numbers.

     When called with no arguments in debugging mode, display the script file currently being debugged.

     An optional range specification can be used to list only a portion of the file.  The special keyword "end" is a valid line number specification for the last line of the file.

     When called with the name of a function, list that script file with line numbers. dblist, dbwhere, dbstatus, dbstop

 -- dblist:
 -- dblist: N
     In debugging mode, list N lines of the function being debugged centered around the current line to be executed.

     If unspecified N defaults to 10 (+/- 5 lines) dbwhere, dbtype, dbstack

You may also use isdebugmode to determine whether the debugger is currently active.

 -- TF =: isdebugmode ()
     Return true if in debugging mode, otherwise false. dbwhere, dbstack, dbstatus

Debug mode also allows single line stepping through a function using the command dbstep.

 -- dbstep:
 -- dbstep: N
 -- dbstep: in
 -- dbstep: out
 -- dbnext: ...
     In debugging mode, execute the next N lines of code.

     If N is omitted, execute the next single line of code.  If the next line of code is itself defined in terms of an m-file remain in the existing function.

     Using dbstep in will cause execution of the next line to step into any m-files defined on the next line.

     Using dbstep out will cause execution to continue until the current function returns.

     Programming Note: dbnext is an alias for dbstep and can be used interchangeably. dbcont, dbquit

When in debug mode the RETURN key will execute the last entered command. This is useful, for example, after hitting a breakpoint and entering dbstep once.  After that, one can advance line by line through the code with only a single key stroke.  This feature may be disabled using the auto_repeat_debug_command function.

 -- VAL =: auto_repeat_debug_command ()
 -- OLD_VAL =: auto_repeat_debug_command (NEW_VAL)
 -- OLD_VAL =: auto_repeat_debug_command (NEW_VAL, "local")
     Query or set the internal variable that controls whether debugging commands are automatically repeated when the input line is empty (typing just RET).

     When called from inside a function with the "local" option, the variable is changed locally for the function and any subroutines it calls. The original variable value is restored when exiting the function.

Call Stack
==========

The function being debugged may be the leaf node of a series of function calls. After examining values in the current subroutine it may turn out that the problem occurred in earlier pieces of code.  Use dbup and dbdown to move up and down through the series of function calls to locate where variables first took on the wrong values.  dbstack shows the entire series of function calls and at what level debugging is currently taking place.

 -- dbstack:
 -- dbstack: N
 -- dbstack: -COMPLETENAMES
 -- [STACK, IDX] =: dbstack (...)
     Display or return current debugging function stack information.

     With optional argument N, omit the N innermost stack frames.

     Although accepted, the argument -COMPLETENAMES is silently ignored. Octave always returns absolute filenames.

     The arguments N and -COMPLETENAMES can both be specified and may appear in any order.

     The optional return argument STACK is a struct array with the following fields:

     file
          The name of the m-file where the function code is located.

     name
          The name of the function with a breakpoint.

     line
          The line number of an active breakpoint.

     column
          The column number of the line where the breakpoint begins.

     The return argument IDX specifies which element of the STACK struct array is currently active. dbup, dbdown, dbwhere, dblist, dbstatus

 -- dbup:
 -- dbup: N
     In debugging mode, move up the execution stack N frames.

     If N is omitted, move up one frame. dbstack, dbdown

 -- dbdown:
 -- dbdown: N
     In debugging mode, move down the execution stack N frames.

     If N is omitted, move down one frame. dbstack, dbup

Profiling
=========

Octave supports profiling of code execution on a per-function level.  If profiling is enabled, each call to a function (supporting built-ins, operators, functions in oct- and mex-files, user-defined functions in Octave code and anonymous functions) is recorded while running Octave code.  After that, this data can aid in analyzing the code behavior, and is in particular helpful for finding ``hot spots'' in the code which use up a lot of computation time and are the best targets to spend optimization efforts on.

The main command for profiling is profile, which can be used to start or stop the profiler and also to query collected data afterwards. The data is returned in an Octave data structure which can then be examined or further processed by other routines or tools.

 -- profile: on
 -- profile: off
 -- profile: resume
 -- profile: clear
 -- S =: profile ("status")
 -- T =: profile ("info")
     Control the built-in profiler.

     profile on
          Start the profiler.  Any previously collected data is cleared.

     profile off
          Stop profiling.  The collected data can later be retrieved and examined with T = profile ("info").

     profile clear
          Clear all collected profiler data.

     profile resume
          Restart profiling without clearing the old data.  All newly collected statistics are added to the existing ones.

     S = profile ("status")
          Return a structure with information about the current status of the profiler.  At the moment, the only field is ProfilerStatus which is either "on" or "off".

     T = profile ("info")
          Return the collected profiling statistics in the structure T.  The flat profile is returned in the field FunctionTable which is an array of structures, each entry corresponding to a function which was called and for which profiling statistics are present.  In addition, the field Hierarchical contains the hierarchical call tree.  Each node has an index into the FunctionTable identifying the function it corresponds to as well as data fields for number of calls and time spent at this level in the call tree.

     profshow, profexplore

An easy way to get an overview over the collected data is profshow.  This function takes the profiler data returned by profile as input and prints a flat profile, for instance:

      Function Attr     Time (s)        Calls
     ----------------------------------------
        >myfib    R        2.195        13529
     binary <=             0.061        13529
      binary -             0.050        13528
      binary +             0.026         6764

This shows that most of the run time was spent executing the function myfib, and some minor proportion evaluating the listed binary operators.  Furthermore, it is shown how often the function was called and the profiler also records that it is recursive.

 -- profshow: (DATA)
 -- profshow: (DATA, N)
 -- profshow: ()
 -- profshow: (N)
     Display flat per-function profiler results.

     Print out profiler data (execution time, number of calls) for the most critical N functions.  The results are sorted in descending order by the total time spent in each function.  If N is unspecified it defaults to 20.

     The input DATA is the structure returned by profile ("info"). If unspecified, profshow will use the current profile dataset.

     The attribute column displays R for recursive functions, and is blank for all other function types. profexplore, profile

 -- profexport: (DIR)
 -- profexport: (DIR, DATA)
 -- profexport: (DIR, NAME)
 -- profexport: (DIR, NAME, DATA)

     Export profiler data as HTML.

     Export the profiling data in DATA into a series of HTML files in the folder DIR.  The initial file will be DATA/index.html.

     If NAME is specified, it must be a string that contains a ``name'' for the profile being exported.  This name is included in the HTML.

     The input DATA is the structure returned by profile ("info"). If unspecified, profexport will use the current profile dataset.

     profshow, profexplore, profile

 -- profexplore: ()
 -- profexplore: (DATA)
     Interactively explore hierarchical profiler output.

     Assuming DATA is the structure with profile data returned by profile ("info"), this command opens an interactive prompt that can be used to explore the call-tree.  Type help to get a list of possible commands.  If DATA is omitted, profile ("info") is called and used in its place. profile, profshow

Profiler Example
================

Below, we will give a short example of a profiler session. See Profiling, for the documentation of the profiler functions in detail.  Consider the code:

     global N A;

     N = 300;
     A = rand (N, N);

     function xt = timesteps (steps, x0, expM)
       global N;

       if (steps == 0)
         xt = NA (N, 0);
       else
         xt = NA (N, steps);
         x1 = expM * x0;
         xt(:, 1) = x1;
         xt(:, 2 : end) = timesteps (steps - 1, x1, expM);
       endif
     endfunction

     function foo ()
       global N A;

       initial = @(x) sin (x);
       x0 = (initial (linspace (0, 2 * pi, N)))';

       expA = expm (A);
       xt = timesteps (100, x0, expA);
     endfunction

     function fib = bar (N)
       if (N <= 2)
         fib = 1;
       else
         fib = bar (N - 1) + bar (N - 2);
       endif
     endfunction

If we execute the two main functions, we get:

     tic; foo; toc;
     => Elapsed time is 2.37338 seconds.

     tic; bar (20); toc;
     => Elapsed time is 2.04952 seconds.

But this does not give much information about where this time is spent; for instance, whether the single call to expm is more expensive or the recursive time-stepping itself.  To get a more detailed picture, we can use the profiler.

     profile on;
     foo;
     profile off;

     data = profile ("info");
     profshow (data, 10);

This prints a table like:

        #  Function Attr     Time (s)        Calls
     ---------------------------------------------
        7      expm             1.034            1
        3  binary *             0.823          117
       41  binary \             0.188            1
       38  binary ^             0.126            2
       43 timesteps    R        0.111          101
       44        NA             0.029          101
       39  binary +             0.024            8
       34      norm             0.011            1
       40  binary -             0.004          101
       33   balance             0.003            1

The entries are the individual functions which have been executed (only the 10 most important ones), together with some information for each of them.  The entries like binary * denote operators, while other entries are ordinary functions.  They include both built-ins like expm and our own routines (for instance timesteps).  From this profile, we can immediately deduce that expm uses up the largest proportion of the processing time, even though it is only called once.  The second expensive operation is the matrix-vector product in the routine timesteps.   (We only know it is the binary multiplication operator, but fortunately this operator appears only at one place in the code and thus we know which occurrence takes so much time.  If there were multiple places, we would have to use the hierarchical profile to find out the exact place which uses up the time which is not covered in this example.)

Timing, however, is not the only information available from the profile. The attribute column shows us that timesteps calls itself recursively.  This may not be that remarkable in this example (since it's clear anyway), but could be helpful in a more complex setting.  As to the question of why is there a binary \ in the output, we can easily shed some light on that too.  Note that data is a structure array (Structure Arrays) which contains the field FunctionTable. This stores the raw data for the profile shown.  The number in the first column of the table gives the index under which the shown function can be found there.  Looking up data.FunctionTable(41) gives:

       scalar structure containing the fields:

         FunctionName = binary \
         TotalTime =  0.18765
         NumCalls =  1
         IsRecursive = 0
         Parents =  7
         Children = [](1x0)

Here we see the information from the table again, but have additional fields Parents and Children.  Those are both arrays, which contain the indices of functions which have directly called the function in question (which is entry 7, expm, in this case) or been called by it (no functions).  Hence, the backslash operator has been used internally by expm.

Now let's take a look at bar.  For this, we start a fresh profiling session (profile on does this; the old data is removed before the profiler is restarted):

     profile on;
     bar (20);
     profile off;

     profshow (profile ("info"));

This gives:

        #            Function Attr     Time (s)        Calls
     -------------------------------------------------------
        1                 bar    R        2.091        13529
        2           binary <=             0.062        13529
        3            binary -             0.042        13528
        4            binary +             0.023         6764
        5             profile             0.000            1
        8               false             0.000            1
        6              nargin             0.000            1
        7           binary !=             0.000            1
        9 __profiler_enable__             0.000            1

Unsurprisingly, bar is also recursive.  It has been called 13,529 times in the course of recursively calculating the Fibonacci number in a suboptimal way, and most of the time was spent in bar itself.

Finally, let's say we want to profile the execution of both foo and bar together.  Since we already have the run-time data collected for bar, we can restart the profiler without clearing the existing data and collect the missing statistics about foo. This is done by:

     profile resume;
     foo;
     profile off;

     profshow (profile ("info"), 10);

As you can see in the table below, now we have both profiles mixed together.

        #  Function Attr     Time (s)        Calls
     ---------------------------------------------
        1       bar    R        2.091        13529
       16      expm             1.122            1
       12  binary *             0.798          117
       46  binary \             0.185            1
       45  binary ^             0.124            2
       48 timesteps    R        0.115          101
        2 binary <=             0.062        13529
        3  binary -             0.045        13629
        4  binary +             0.041         6772
       49        NA             0.036          101