\input texinfo @c -*-texinfo-*-@setfilename gprof.info@c Copyright 1988, 1992, 1993, 1998, 1999, 2000, 2001, 2002, 2003, 2004@c Free Software Foundation, Inc.@settitle GNU gprof@setchapternewpage odd@ifinfo@c This is a dir.info fragment to support semi-automated addition of@c manuals to an info tree. zoo@cygnus.com is developing this facility.@formatSTART-INFO-DIR-ENTRY* gprof: (gprof). Profiling your program's executionEND-INFO-DIR-ENTRY@end format@end ifinfo@ifinfoThis file documents the gprof profiler of the GNU system.@c man begin COPYRIGHTCopyright (C) 1988, 92, 97, 98, 99, 2000, 2001, 2003 Free Software Foundation, Inc.Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.1or any later version published by the Free Software Foundation;with no Invariant Sections, with no Front-Cover Texts, and with noBack-Cover Texts. A copy of the license is included in thesection entitled "GNU Free Documentation License".@c man end@ignorePermission is granted to process this file through Tex and print theresults, provided the printed document carries copying permissionnotice identical to this one except for the removal of this paragraph(this paragraph not being relevant to the printed manual).@end ignore@end ifinfo@finalout@smallbook@titlepage@title GNU gprof@subtitle The @sc{gnu} Profiler@author Jay Fenlason and Richard Stallman@pageThis manual describes the @sc{gnu} profiler, @code{gprof}, and how youcan use it to determine which parts of a program are taking most of theexecution time. We assume that you know how to write, compile, andexecute programs. @sc{gnu} @code{gprof} was written by Jay Fenlason.Eric S. Raymond made some minor corrections and additions in 2003.@vskip 0pt plus 1filllCopyright @copyright{} 1988, 92, 97, 98, 99, 2000, 2003 Free Software Foundation, Inc.Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.1or any later version published by the Free Software Foundation;with no Invariant Sections, with no Front-Cover Texts, and with noBack-Cover Texts. A copy of the license is included in thesection entitled "GNU Free Documentation License".@end titlepage@ifnottex@node Top@top Profiling a Program: Where Does It Spend Its Time?This manual describes the @sc{gnu} profiler, @code{gprof}, and how youcan use it to determine which parts of a program are taking most of theexecution time. We assume that you know how to write, compile, andexecute programs. @sc{gnu} @code{gprof} was written by Jay Fenlason.This document is distributed under the terms of the GNU FreeDocumentation License. A copy of the license is included in thesection entitled "GNU Free Documentation License".@menu* Introduction:: What profiling means, and why it is useful.* Compiling:: How to compile your program for profiling.* Executing:: Executing your program to generate profile data* Invoking:: How to run @code{gprof}, and its options* Output:: Interpreting @code{gprof}'s output* Inaccuracy:: Potential problems you should be aware of* How do I?:: Answers to common questions* Incompatibilities:: (between @sc{gnu} @code{gprof} and Unix @code{gprof}.)* Details:: Details of how profiling is done* GNU Free Documentation License:: GNU Free Documentation License@end menu@end ifnottex@node Introduction@chapter Introduction to Profiling@ifset man@c man title gprof display call graph profile data@smallexample@c man begin SYNOPSISgprof [ -[abcDhilLrsTvwxyz] ] [ -[ACeEfFJnNOpPqQZ][@var{name}] ][ -I @var{dirs} ] [ -d[@var{num}] ] [ -k @var{from/to} ][ -m @var{min-count} ] [ -R @var{map_file} ] [ -t @var{table-length} ][ --[no-]annotated-source[=@var{name}] ][ --[no-]exec-counts[=@var{name}] ][ --[no-]flat-profile[=@var{name}] ] [ --[no-]graph[=@var{name}] ][ --[no-]time=@var{name}] [ --all-lines ] [ --brief ][ --debug[=@var{level}] ] [ --function-ordering ][ --file-ordering ] [ --directory-path=@var{dirs} ][ --display-unused-functions ] [ --file-format=@var{name} ][ --file-info ] [ --help ] [ --line ] [ --min-count=@var{n} ][ --no-static ] [ --print-path ] [ --separate-files ][ --static-call-graph ] [ --sum ] [ --table-length=@var{len} ][ --traditional ] [ --version ] [ --width=@var{n} ][ --ignore-non-functions ] [ --demangle[=@var{STYLE}] ][ --no-demangle ] [ @var{image-file} ] [ @var{profile-file} @dots{} ]@c man end@end smallexample@c man begin DESCRIPTION@code{gprof} produces an execution profile of C, Pascal, or Fortran77programs. The effect of called routines is incorporated in the profileof each caller. The profile data is taken from the call graph profile file(@file{gmon.out} default) which is created by programsthat are compiled with the @samp{-pg} option of@code{cc}, @code{pc}, and @code{f77}.The @samp{-pg} option also links in versions of the library routinesthat are compiled for profiling. @code{Gprof} reads the given objectfile (the default is @code{a.out}) and establishes the relation betweenits symbol table and the call graph profile from @file{gmon.out}.If more than one profile file is specified, the @code{gprof}output shows the sum of the profile information in the given profile files.@code{Gprof} calculates the amount of time spent in each routine.Next, these times are propagated along the edges of the call graph.Cycles are discovered, and calls into a cycle are made to share the timeof the cycle.@c man end@c man begin BUGSThe granularity of the sampling is shown, but remainsstatistical at best.We assume that the time for each execution of a functioncan be expressed by the total time for the function dividedby the number of times the function is called.Thus the time propagated along the call graph arcs to the function'sparents is directly proportional to the number of times thatarc is traversed.Parents that are not themselves profiled will have the time oftheir profiled children propagated to them, but they will appearto be spontaneously invoked in the call graph listing, and willnot have their time propagated further.Similarly, signal catchers, even though profiled, will appearto be spontaneous (although for more obscure reasons).Any profiled children of signal catchers should have their timespropagated properly, unless the signal catcher was invoked duringthe execution of the profiling routine, in which case all is lost.The profiled program must call @code{exit}(2)or return normally for the profiling information to be savedin the @file{gmon.out} file.@c man end@c man begin FILES@table @code@item @file{a.out}the namelist and text space.@item @file{gmon.out}dynamic call graph and profile.@item @file{gmon.sum}summarized dynamic call graph and profile.@end table@c man end@c man begin SEEALSOmonitor(3), profil(2), cc(1), prof(1), and the Info entry for @file{gprof}.``An Execution Profiler for Modular Programs'',by S. Graham, P. Kessler, M. McKusick;Software - Practice and Experience,Vol. 13, pp. 671-685, 1983.``gprof: A Call Graph Execution Profiler'',by S. Graham, P. Kessler, M. McKusick;Proceedings of the SIGPLAN '82 Symposium on Compiler Construction,SIGPLAN Notices, Vol. 17, No 6, pp. 120-126, June 1982.@c man end@end ifsetProfiling allows you to learn where your program spent its time and whichfunctions called which other functions while it was executing. Thisinformation can show you which pieces of your program are slower than youexpected, and might be candidates for rewriting to make your programexecute faster. It can also tell you which functions are being called moreor less often than you expected. This may help you spot bugs that hadotherwise been unnoticed.Since the profiler uses information collected during the actual executionof your program, it can be used on programs that are too large or toocomplex to analyze by reading the source. However, how your program is runwill affect the information that shows up in the profile data. If youdon't use some feature of your program while it is being profiled, noprofile information will be generated for that feature.Profiling has several steps:@itemize @bullet@itemYou must compile and link your program with profiling enabled.@xref{Compiling}.@itemYou must execute your program to generate a profile data file.@xref{Executing}.@itemYou must run @code{gprof} to analyze the profile data.@xref{Invoking}.@end itemizeThe next three chapters explain these steps in greater detail.@c man begin DESCRIPTIONSeveral forms of output are available from the analysis.The @dfn{flat profile} shows how much time your program spent in each function,and how many times that function was called. If you simply want to knowwhich functions burn most of the cycles, it is stated concisely here.@xref{Flat Profile}.The @dfn{call graph} shows, for each function, which functions called it, whichother functions it called, and how many times. There is also an estimateof how much time was spent in the subroutines of each function. This cansuggest places where you might try to eliminate function calls that use alot of time. @xref{Call Graph}.The @dfn{annotated source} listing is a copy of the program'ssource code, labeled with the number of times each line of theprogram was executed. @xref{Annotated Source}.@c man endTo better understand how profiling works, you may wish to reada description of its implementation.@xref{Implementation}.@node Compiling@chapter Compiling a Program for ProfilingThe first step in generating profile information for your program isto compile and link it with profiling enabled.To compile a source file for profiling, specify the @samp{-pg} option whenyou run the compiler. (This is in addition to the options you normallyuse.)To link the program for profiling, if you use a compiler such as @code{cc}to do the linking, simply specify @samp{-pg} in addition to your usualoptions. The same option, @samp{-pg}, alters either compilation or linkingto do what is necessary for profiling. Here are examples:@examplecc -g -c myprog.c utils.c -pgcc -o myprog myprog.o utils.o -pg@end exampleThe @samp{-pg} option also works with a command that both compiles and links:@examplecc -o myprog myprog.c utils.c -g -pg@end exampleNote: The @samp{-pg} option must be part of your compilation optionsas well as your link options. If it is not then no call-graph datawill be gathered and when you run @code{gprof} you will get an errormessage like this:@examplegprof: gmon.out file is missing call-graph data@end exampleIf you add the @samp{-Q} switch to suppress the printing of the callgraph data you will still be able to see the time samples:@exampleFlat profile:Each sample counts as 0.01 seconds.% cumulative self self totaltime seconds seconds calls Ts/call Ts/call name44.12 0.07 0.07 zazLoop35.29 0.14 0.06 main20.59 0.17 0.04 bazMillion% the percentage of the total running time of the@end exampleIf you run the linker @code{ld} directly instead of through a compilersuch as @code{cc}, you may have to specify a profiling startup file@file{gcrt0.o} as the first input file instead of the usual startupfile @file{crt0.o}. In addition, you would probably want tospecify the profiling C library, @file{libc_p.a}, by writing@samp{-lc_p} instead of the usual @samp{-lc}. This is not absolutelynecessary, but doing this gives you number-of-calls information forstandard library functions such as @code{read} and @code{open}. Forexample:@exampleld -o myprog /lib/gcrt0.o myprog.o utils.o -lc_p@end exampleIf you compile only some of the modules of the program with @samp{-pg}, youcan still profile the program, but you won't get complete information aboutthe modules that were compiled without @samp{-pg}. The only informationyou get for the functions in those modules is the total time spent in them;there is no record of how many times they were called, or from where. Thiswill not affect the flat profile (except that the @code{calls} field forthe functions will be blank), but will greatly reduce the usefulness of thecall graph.If you wish to perform line-by-line profiling,you will also need to specify the @samp{-g} option,instructing the compiler to insert debugging symbols into the programthat match program addresses to source code lines.@xref{Line-by-line}.In addition to the @samp{-pg} and @samp{-g} options, older versions ofGCC required you to specify the @samp{-a} option when compiling inorder to instrument it to perform basic-block counting. Newerversions do not require this option and will not accept it;basic-block counting is always enabled when @samp{-pg} is on.When basic-block counting is enabled, as the program runsit will count how many times it executed each branch of each @samp{if}statement, each iteration of each @samp{do} loop, etc. This willenable @code{gprof} to construct an annotated source codelisting showing how many times each line of code was executed.It also worth noting that GCC supports a different profiling methodwhich is enabled by the @samp{-fprofile-arcs}, @samp{-ftest-coverage}and @samp{-fprofile-values} switches. These switches do not producedata which is useful to @code{gprof} however, so they are notdiscussed further here. There is also the@samp{-finstrument-functions} switch which will cause GCC to insertcalls to special user supplied instrumentation routines at the entryand exit of every function in their program. This can be used toimplement an alternative profiling scheme.@node Executing@chapter Executing the ProgramOnce the program is compiled for profiling, you must run it in order togenerate the information that @code{gprof} needs. Simply run the programas usual, using the normal arguments, file names, etc. The program shouldrun normally, producing the same output as usual. It will, however, runsomewhat slower than normal because of the time spent collecting and thewriting the profile data.The way you run the program---the arguments and input that you giveit---may have a dramatic effect on what the profile information shows. Theprofile data will describe the parts of the program that were activated forthe particular input you use. For example, if the first command you giveto your program is to quit, the profile data will show the time used ininitialization and in cleanup, but not much else.Your program will write the profile data into a file called @file{gmon.out}just before exiting. If there is already a file called @file{gmon.out},its contents are overwritten. There is currently no way to tell theprogram to write the profile data under a different name, but you can renamethe file afterwards if you are concerned that it may be overwritten.In order to write the @file{gmon.out} file properly, your program must exitnormally: by returning from @code{main} or by calling @code{exit}. Callingthe low-level function @code{_exit} does not write the profile data, andneither does abnormal termination due to an unhandled signal.The @file{gmon.out} file is written in the program's @emph{current workingdirectory} at the time it exits. This means that if your program calls@code{chdir}, the @file{gmon.out} file will be left in the last directoryyour program @code{chdir}'d to. If you don't have permission to write inthis directory, the file is not written, and you will get an error message.Older versions of the @sc{gnu} profiling library may also write a filecalled @file{bb.out}. This file, if present, contains an human-readablelisting of the basic-block execution counts. Unfortunately, theappearance of a human-readable @file{bb.out} means the basic-blockcounts didn't get written into @file{gmon.out}.The Perl script @code{bbconv.pl}, included with the @code{gprof}source distribution, will convert a @file{bb.out} file intoa format readable by @code{gprof}. Invoke it like this:@smallexamplebbconv.pl < bb.out > @var{bh-data}@end smallexampleThis translates the information in @file{bb.out} into a form that@code{gprof} can understand. But you still need to tell @code{gprof}about the existence of this translated information. To do that, include@var{bb-data} on the @code{gprof} command line, @emph{along with@file{gmon.out}}, like this:@smallexamplegprof @var{options} @var{executable-file} gmon.out @var{bb-data} [@var{yet-more-profile-data-files}@dots{}] [> @var{outfile}]@end smallexample@node Invoking@chapter @code{gprof} Command SummaryAfter you have a profile data file @file{gmon.out}, you can run @code{gprof}to interpret the information in it. The @code{gprof} program prints aflat profile and a call graph on standard output. Typically you wouldredirect the output of @code{gprof} into a file with @samp{>}.You run @code{gprof} like this:@smallexamplegprof @var{options} [@var{executable-file} [@var{profile-data-files}@dots{}]] [> @var{outfile}]@end smallexample@noindentHere square-brackets indicate optional arguments.If you omit the executable file name, the file @file{a.out} is used. Ifyou give no profile data file name, the file @file{gmon.out} is used. Ifany file is not in the proper format, or if the profile data file does notappear to belong to the executable file, an error message is printed.You can give more than one profile data file by entering all their namesafter the executable file name; then the statistics in all the data filesare summed together.The order of these options does not matter.@menu* Output Options:: Controlling @code{gprof}'s output style* Analysis Options:: Controlling how @code{gprof} analyses its data* Miscellaneous Options::* Deprecated Options:: Options you no longer need to use, but whichhave been retained for compatibility* Symspecs:: Specifying functions to include or exclude@end menu@node Output Options,Analysis Options,,Invoking@section Output Options@c man begin OPTIONSThese options specify which of several output formats@code{gprof} should produce.Many of these options take an optional @dfn{symspec} to specifyfunctions to be included or excluded. These options can bespecified multiple times, with different symspecs, to includeor exclude sets of symbols. @xref{Symspecs}.Specifying any of these options overrides the default (@samp{-p -q}),which prints a flat profile and call graph analysisfor all functions.@table @code@item -A[@var{symspec}]@itemx --annotated-source[=@var{symspec}]The @samp{-A} option causes @code{gprof} to print annotated source code.If @var{symspec} is specified, print output only for matching symbols.@xref{Annotated Source}.@item -b@itemx --briefIf the @samp{-b} option is given, @code{gprof} doesn't print theverbose blurbs that try to explain the meaning of all of the fields inthe tables. This is useful if you intend to print out the output, orare tired of seeing the blurbs.@item -C[@var{symspec}]@itemx --exec-counts[=@var{symspec}]The @samp{-C} option causes @code{gprof} toprint a tally of functions and the number of times each was called.If @var{symspec} is specified, print tally only for matching symbols.If the profile data file contains basic-block count records, specifyingthe @samp{-l} option, along with @samp{-C}, will cause basic-blockexecution counts to be tallied and displayed.@item -i@itemx --file-infoThe @samp{-i} option causes @code{gprof} to display summary informationabout the profile data file(s) and then exit. The number of histogram,call graph, and basic-block count records is displayed.@item -I @var{dirs}@itemx --directory-path=@var{dirs}The @samp{-I} option specifies a list of search directories inwhich to find source files. Environment variable @var{GPROF_PATH}can also be used to convey this information.Used mostly for annotated source output.@item -J[@var{symspec}]@itemx --no-annotated-source[=@var{symspec}]The @samp{-J} option causes @code{gprof} not toprint annotated source code.If @var{symspec} is specified, @code{gprof} prints annotated source,but excludes matching symbols.@item -L@itemx --print-pathNormally, source filenames are printed with the pathcomponent suppressed. The @samp{-L} option causes @code{gprof}to print the full pathname ofsource filenames, which is determinedfrom symbolic debugging information in the image fileand is relative to the directory in which the compilerwas invoked.@item -p[@var{symspec}]@itemx --flat-profile[=@var{symspec}]The @samp{-p} option causes @code{gprof} to print a flat profile.If @var{symspec} is specified, print flat profile only for matching symbols.@xref{Flat Profile}.@item -P[@var{symspec}]@itemx --no-flat-profile[=@var{symspec}]The @samp{-P} option causes @code{gprof} to suppress printing a flat profile.If @var{symspec} is specified, @code{gprof} prints a flat profile,but excludes matching symbols.@item -q[@var{symspec}]@itemx --graph[=@var{symspec}]The @samp{-q} option causes @code{gprof} to print the call graph analysis.If @var{symspec} is specified, print call graph only for matching symbolsand their children.@xref{Call Graph}.@item -Q[@var{symspec}]@itemx --no-graph[=@var{symspec}]The @samp{-Q} option causes @code{gprof} to suppress printing thecall graph.If @var{symspec} is specified, @code{gprof} prints a call graph,but excludes matching symbols.@item -t@itemx --table-length=@var{num}The @samp{-t} option causes the @var{num} most active source lines ineach source file to be listed when source annotation is enabled. Thedefault is 10.@item -y@itemx --separate-filesThis option affects annotated source output only.Normally, @code{gprof} prints annotated source filesto standard-output. If this option is specified,annotated source for a file named @file{path/@var{filename}}is generated in the file @file{@var{filename}-ann}. If the underlyingfilesystem would truncate @file{@var{filename}-ann} so that itoverwrites the original @file{@var{filename}}, @code{gprof} generatesannotated source in the file @file{@var{filename}.ann} instead (if theoriginal file name has an extension, that extension is @emph{replaced}with @file{.ann}).@item -Z[@var{symspec}]@itemx --no-exec-counts[=@var{symspec}]The @samp{-Z} option causes @code{gprof} not toprint a tally of functions and the number of times each was called.If @var{symspec} is specified, print tally, but exclude matching symbols.@item -r@itemx --function-orderingThe @samp{--function-ordering} option causes @code{gprof} to print asuggested function ordering for the program based on profiling data.This option suggests an ordering which may improve paging, tlb andcache behavior for the program on systems which support arbitraryordering of functions in an executable.The exact details of how to force the linker to place functionsin a particular order is system dependent and out of the scope of thismanual.@item -R @var{map_file}@itemx --file-ordering @var{map_file}The @samp{--file-ordering} option causes @code{gprof} to print asuggested .o link line ordering for the program based on profiling data.This option suggests an ordering which may improve paging, tlb andcache behavior for the program on systems which do not support arbitraryordering of functions in an executable.Use of the @samp{-a} argument is highly recommended with this option.The @var{map_file} argument is a pathname to a file which providesfunction name to object file mappings. The format of the file is similar tothe output of the program @code{nm}.@smallexample@groupc-parse.o:00000000 T yyparsec-parse.o:00000004 C yyerrflagc-lang.o:00000000 T maybe_objc_method_namec-lang.o:00000000 T print_lang_statisticsc-lang.o:00000000 T recognize_objc_keywordc-decl.o:00000000 T print_lang_identifierc-decl.o:00000000 T print_lang_type@dots{}@end group@end smallexampleTo create a @var{map_file} with @sc{gnu} @code{nm}, type a command like@kbd{nm --extern-only --defined-only -v --print-file-name program-name}.@item -T@itemx --traditionalThe @samp{-T} option causes @code{gprof} to print its output in``traditional'' BSD style.@item -w @var{width}@itemx --width=@var{width}Sets width of output lines to @var{width}.Currently only used when printing the function index at the bottomof the call graph.@item -x@itemx --all-linesThis option affects annotated source output only.By default, only the lines at the beginning of a basic-blockare annotated. If this option is specified, every line ina basic-block is annotated by repeating the annotation for thefirst line. This behavior is similar to @code{tcov}'s @samp{-a}.@item --demangle[=@var{style}]@itemx --no-demangleThese options control whether C++ symbol names should be demangled whenprinting output. The default is to demangle symbols. The@code{--no-demangle} option may be used to turn off demangling. Differentcompilers have different mangling styles. The optional demangling styleargument can be used to choose an appropriate demangling style for yourcompiler.@end table@node Analysis Options,Miscellaneous Options,Output Options,Invoking@section Analysis Options@table @code@item -a@itemx --no-staticThe @samp{-a} option causes @code{gprof} to suppress the printing ofstatically declared (private) functions. (These are functions whosenames are not listed as global, and which are not visible outside thefile/function/block where they were defined.) Time spent in thesefunctions, calls to/from them, etc, will all be attributed to thefunction that was loaded directly before it in the executable file.@c This is compatible with Unix @code{gprof}, but a bad idea.This option affects both the flat profile and the call graph.@item -c@itemx --static-call-graphThe @samp{-c} option causes the call graph of the program to beaugmented by a heuristic which examines the text space of the objectfile and identifies function calls in the binary machine code.Since normal call graph records are only generated when functions areentered, this option identifies children that could have been called,but never were. Calls to functions that were not compiled withprofiling enabled are also identified, but only if symbol tableentries are present for them.Calls to dynamic library routines are typically @emph{not} foundby this option.Parents or children identified via this heuristicare indicated in the call graph with call counts of @samp{0}.@item -D@itemx --ignore-non-functionsThe @samp{-D} option causes @code{gprof} to ignore symbols whichare not known to be functions. This option will give more accurateprofile data on systems where it is supported (Solaris and HPUX forexample).@item -k @var{from}/@var{to}The @samp{-k} option allows you to delete from the call graph any arcs fromsymbols matching symspec @var{from} to those matching symspec @var{to}.@item -l@itemx --lineThe @samp{-l} option enables line-by-line profiling, which causeshistogram hits to be charged to individual source code lines,instead of functions.If the program was compiled with basic-block counting enabled,this option will also identify how many times each line ofcode was executed.While line-by-line profiling can help isolate where in a large functiona program is spending its time, it also significantly increasesthe running time of @code{gprof}, and magnifies statisticalinaccuracies.@xref{Sampling Error}.@item -m @var{num}@itemx --min-count=@var{num}This option affects execution count output only.Symbols that are executed less than @var{num} times are suppressed.@item -n[@var{symspec}]@itemx --time[=@var{symspec}]The @samp{-n} option causes @code{gprof}, in its call graph analysis,to only propagate times for symbols matching @var{symspec}.@item -N[@var{symspec}]@itemx --no-time[=@var{symspec}]The @samp{-n} option causes @code{gprof}, in its call graph analysis,not to propagate times for symbols matching @var{symspec}.@item -z@itemx --display-unused-functionsIf you give the @samp{-z} option, @code{gprof} will mention allfunctions in the flat profile, even those that were never called, andthat had no time spent in them. This is useful in conjunction with the@samp{-c} option for discovering which routines were never called.@end table@node Miscellaneous Options,Deprecated Options,Analysis Options,Invoking@section Miscellaneous Options@table @code@item -d[@var{num}]@itemx --debug[=@var{num}]The @samp{-d @var{num}} option specifies debugging options.If @var{num} is not specified, enable all debugging.@xref{Debugging}.@item -h@itemx --helpThe @samp{-h} option prints command line usage.@item -O@var{name}@itemx --file-format=@var{name}Selects the format of the profile data files. Recognized formats are@samp{auto} (the default), @samp{bsd}, @samp{4.4bsd}, @samp{magic}, and@samp{prof} (not yet supported).@item -s@itemx --sumThe @samp{-s} option causes @code{gprof} to summarize the informationin the profile data files it read in, and write out a profile datafile called @file{gmon.sum}, which contains all the information fromthe profile data files that @code{gprof} read in. The file @file{gmon.sum}may be one of the specified input files; the effect of this is tomerge the data in the other input files into @file{gmon.sum}.Eventually you can run @code{gprof} again without @samp{-s} to analyze thecumulative data in the file @file{gmon.sum}.@item -v@itemx --versionThe @samp{-v} flag causes @code{gprof} to print the current versionnumber, and then exit.@end table@node Deprecated Options,Symspecs,Miscellaneous Options,Invoking@section Deprecated Options@table @codeThese options have been replaced with newer versions that use symspecs.@item -e @var{function_name}The @samp{-e @var{function}} option tells @code{gprof} to not printinformation about the function @var{function_name} (and itschildren@dots{}) in the call graph. The function will still be listedas a child of any functions that call it, but its index number will beshown as @samp{[not printed]}. More than one @samp{-e} option may begiven; only one @var{function_name} may be indicated with each @samp{-e}option.@item -E @var{function_name}The @code{-E @var{function}} option works like the @code{-e} option, buttime spent in the function (and children who were not called fromanywhere else), will not be used to compute the percentages-of-time forthe call graph. More than one @samp{-E} option may be given; only one@var{function_name} may be indicated with each @samp{-E} option.@item -f @var{function_name}The @samp{-f @var{function}} option causes @code{gprof} to limit thecall graph to the function @var{function_name} and its children (andtheir children@dots{}). More than one @samp{-f} option may be given;only one @var{function_name} may be indicated with each @samp{-f}option.@item -F @var{function_name}The @samp{-F @var{function}} option works like the @code{-f} option, butonly time spent in the function and its children (and theirchildren@dots{}) will be used to determine total-time andpercentages-of-time for the call graph. More than one @samp{-F} optionmay be given; only one @var{function_name} may be indicated with each@samp{-F} option. The @samp{-F} option overrides the @samp{-E} option.@end table@c man endNote that only one function can be specified with each @code{-e},@code{-E}, @code{-f} or @code{-F} option. To specify more than onefunction, use multiple options. For example, this command:@examplegprof -e boring -f foo -f bar myprogram > gprof.output@end example@noindentlists in the call graph all functions that were reached from either@code{foo} or @code{bar} and were not reachable from @code{boring}.@node Symspecs,,Deprecated Options,Invoking@section SymspecsMany of the output options allow functions to be included or excludedusing @dfn{symspecs} (symbol specifications), which observe thefollowing syntax:@examplefilename_containing_a_dot| funcname_not_containing_a_dot| linenumber| ( [ any_filename ] `:' ( any_funcname | linenumber ) )@end exampleHere are some sample symspecs:@table @samp@item main.cSelects everything in file @file{main.c}---thedot in the string tells @code{gprof} to interpretthe string as a filename, rather than asa function name. To select a file whosename does not contain a dot, a trailing colonshould be specified. For example, @samp{odd:} isinterpreted as the file named @file{odd}.@item mainSelects all functions named @samp{main}.Note that there may be multiple instances of the same function namebecause some of the definitions may be local (i.e., static). Unless afunction name is unique in a program, you must use the colon notationexplained below to specify a function from a specific source file.Sometimes, function names contain dots. In such cases, it is necessaryto add a leading colon to the name. For example, @samp{:.mul} selectsfunction @samp{.mul}.In some object file formats, symbols have a leading underscore.@code{gprof} will normally not print these underscores. When you name asymbol in a symspec, you should type it exactly as @code{gprof} printsit in its output. For example, if the compiler produces a symbol@samp{_main} from your @code{main} function, @code{gprof} still printsit as @samp{main} in its output, so you should use @samp{main} insymspecs.@item main.c:mainSelects function @samp{main} in file @file{main.c}.@item main.c:134Selects line 134 in file @file{main.c}.@end table@node Output@chapter Interpreting @code{gprof}'s Output@code{gprof} can produce several different output styles, themost important of which are described below. The simplest outputstyles (file information, execution count, and function and file ordering)are not described here, but are documented with the respective optionsthat trigger them.@xref{Output Options}.@menu* Flat Profile:: The flat profile shows how much time was spentexecuting directly in each function.* Call Graph:: The call graph shows which functions called whichothers, and how much time each function usedwhen its subroutine calls are included.* Line-by-line:: @code{gprof} can analyze individual source code lines* Annotated Source:: The annotated source listing displays source codelabeled with execution counts@end menu@node Flat Profile,Call Graph,,Output@section The Flat Profile@cindex flat profileThe @dfn{flat profile} shows the total amount of time your programspent executing each function. Unless the @samp{-z} option is given,functions with no apparent time spent in them, and no apparent callsto them, are not mentioned. Note that if a function was not compiledfor profiling, and didn't run long enough to show up on the programcounter histogram, it will be indistinguishable from a function thatwas never called.This is part of a flat profile for a small program:@smallexample@groupFlat profile:Each sample counts as 0.01 seconds.% cumulative self self totaltime seconds seconds calls ms/call ms/call name33.34 0.02 0.02 7208 0.00 0.00 open16.67 0.03 0.01 244 0.04 0.12 offtime16.67 0.04 0.01 8 1.25 1.25 memccpy16.67 0.05 0.01 7 1.43 1.43 write16.67 0.06 0.01 mcount0.00 0.06 0.00 236 0.00 0.00 tzset0.00 0.06 0.00 192 0.00 0.00 tolower0.00 0.06 0.00 47 0.00 0.00 strlen0.00 0.06 0.00 45 0.00 0.00 strchr0.00 0.06 0.00 1 0.00 50.00 main0.00 0.06 0.00 1 0.00 0.00 memcpy0.00 0.06 0.00 1 0.00 10.11 print0.00 0.06 0.00 1 0.00 0.00 profil0.00 0.06 0.00 1 0.00 50.00 report@dots{}@end group@end smallexample@noindentThe functions are sorted by first by decreasing run-time spent in them,then by decreasing number of calls, then alphabetically by name. Thefunctions @samp{mcount} and @samp{profil} are part of the profilingapparatus and appear in every flat profile; their time gives a measure ofthe amount of overhead due to profiling.Just before the column headers, a statement appears indicatinghow much time each sample counted as.This @dfn{sampling period} estimates the margin of error in each of the timefigures. A time figure that is not much larger than this is notreliable. In this example, each sample counted as 0.01 seconds,suggesting a 100 Hz sampling rate.The program's total execution time was 0.06seconds, as indicated by the @samp{cumulative seconds} field. Sinceeach sample counted for 0.01 seconds, this means only six sampleswere taken during the run. Two of the samples occurred while theprogram was in the @samp{open} function, as indicated by the@samp{self seconds} field. Each of the other four samplesoccurred one each in @samp{offtime}, @samp{memccpy}, @samp{write},and @samp{mcount}.Since only six samples were taken, none of these values canbe regarded as particularly reliable.In another run,the @samp{self seconds} field for@samp{mcount} might well be @samp{0.00} or @samp{0.02}.@xref{Sampling Error}, for a complete discussion.The remaining functions in the listing (those whose@samp{self seconds} field is @samp{0.00}) didn't appearin the histogram samples at all. However, the call graphindicated that they were called, so therefore they are listed,sorted in decreasing order by the @samp{calls} field.Clearly some time was spent executing these functions,but the paucity of histogram samples prevents anydetermination of how much time each took.Here is what the fields in each line mean:@table @code@item % timeThis is the percentage of the total execution time your program spentin this function. These should all add up to 100%.@item cumulative secondsThis is the cumulative total number of seconds the computer spentexecuting this functions, plus the time spent in all the functionsabove this one in this table.@item self secondsThis is the number of seconds accounted for by this function alone.The flat profile listing is sorted first by this number.@item callsThis is the total number of times the function was called. If thefunction was never called, or the number of times it was called cannotbe determined (probably because the function was not compiled withprofiling enabled), the @dfn{calls} field is blank.@item self ms/callThis represents the average number of milliseconds spent in thisfunction per call, if this function is profiled. Otherwise, this fieldis blank for this function.@item total ms/callThis represents the average number of milliseconds spent in thisfunction and its descendants per call, if this function is profiled.Otherwise, this field is blank for this function.This is the only field in the flat profile that uses call graph analysis.@item nameThis is the name of the function. The flat profile is sorted by thisfield alphabetically after the @dfn{self seconds} and @dfn{calls}fields are sorted.@end table@node Call Graph,Line-by-line,Flat Profile,Output@section The Call Graph@cindex call graphThe @dfn{call graph} shows how much time was spent in each functionand its children. From this information, you can find functions that,while they themselves may not have used much time, called otherfunctions that did use unusual amounts of time.Here is a sample call from a small program. This call came from thesame @code{gprof} run as the flat profile example in the previouschapter.@smallexample@groupgranularity: each sample hit covers 2 byte(s) for 20.00% of 0.05 secondsindex % time self children called name<spontaneous>[1] 100.0 0.00 0.05 start [1]0.00 0.05 1/1 main [2]0.00 0.00 1/2 on_exit [28]0.00 0.00 1/1 exit [59]-----------------------------------------------0.00 0.05 1/1 start [1][2] 100.0 0.00 0.05 1 main [2]0.00 0.05 1/1 report [3]-----------------------------------------------0.00 0.05 1/1 main [2][3] 100.0 0.00 0.05 1 report [3]0.00 0.03 8/8 timelocal [6]0.00 0.01 1/1 print [9]0.00 0.01 9/9 fgets [12]0.00 0.00 12/34 strncmp <cycle 1> [40]0.00 0.00 8/8 lookup [20]0.00 0.00 1/1 fopen [21]0.00 0.00 8/8 chewtime [24]0.00 0.00 8/16 skipspace [44]-----------------------------------------------[4] 59.8 0.01 0.02 8+472 <cycle 2 as a whole> [4]0.01 0.02 244+260 offtime <cycle 2> [7]0.00 0.00 236+1 tzset <cycle 2> [26]-----------------------------------------------@end group@end smallexampleThe lines full of dashes divide this table into @dfn{entries}, one for eachfunction. Each entry has one or more lines.In each entry, the primary line is the one that starts with an index numberin square brackets. The end of this line says which function the entry isfor. The preceding lines in the entry describe the callers of thisfunction and the following lines describe its subroutines (also called@dfn{children} when we speak of the call graph).The entries are sorted by time spent in the function and its subroutines.The internal profiling function @code{mcount} (@pxref{Flat Profile})is never mentioned in the call graph.@menu* Primary:: Details of the primary line's contents.* Callers:: Details of caller-lines' contents.* Subroutines:: Details of subroutine-lines' contents.* Cycles:: When there are cycles of recursion,such as @code{a} calls @code{b} calls @code{a}@dots{}@end menu@node Primary@subsection The Primary LineThe @dfn{primary line} in a call graph entry is the line thatdescribes the function which the entry is about and gives the overallstatistics for this function.For reference, we repeat the primary line from the entry for function@code{report} in our main example, together with the heading line thatshows the names of the fields:@smallexample@groupindex % time self children called name@dots{}[3] 100.0 0.00 0.05 1 report [3]@end group@end smallexampleHere is what the fields in the primary line mean:@table @code@item indexEntries are numbered with consecutive integers. Each functiontherefore has an index number, which appears at the beginning of itsprimary line.Each cross-reference to a function, as a caller or subroutine ofanother, gives its index number as well as its name. The index numberguides you if you wish to look for the entry for that function.@item % timeThis is the percentage of the total time that was spent in thisfunction, including time spent in subroutines called from thisfunction.The time spent in this function is counted again for the callers ofthis function. Therefore, adding up these percentages is meaningless.@item selfThis is the total amount of time spent in this function. Thisshould be identical to the number printed in the @code{seconds} fieldfor this function in the flat profile.@item childrenThis is the total amount of time spent in the subroutine calls made bythis function. This should be equal to the sum of all the @code{self}and @code{children} entries of the children listed directly below thisfunction.@item calledThis is the number of times the function was called.If the function called itself recursively, there are two numbers,separated by a @samp{+}. The first number counts non-recursive calls,and the second counts recursive calls.In the example above, the function @code{report} was called once from@code{main}.@item nameThis is the name of the current function. The index number isrepeated after it.If the function is part of a cycle of recursion, the cycle number isprinted between the function's name and the index number(@pxref{Cycles}). For example, if function @code{gnurr} is part ofcycle number one, and has index number twelve, its primary line wouldbe end like this:@examplegnurr <cycle 1> [12]@end example@end table@node Callers, Subroutines, Primary, Call Graph@subsection Lines for a Function's CallersA function's entry has a line for each function it was called by.These lines' fields correspond to the fields of the primary line, buttheir meanings are different because of the difference in context.For reference, we repeat two lines from the entry for the function@code{report}, the primary line and one caller-line preceding it, togetherwith the heading line that shows the names of the fields:@smallexampleindex % time self children called name@dots{}0.00 0.05 1/1 main [2][3] 100.0 0.00 0.05 1 report [3]@end smallexampleHere are the meanings of the fields in the caller-line for @code{report}called from @code{main}:@table @code@item selfAn estimate of the amount of time spent in @code{report} itself when it wascalled from @code{main}.@item childrenAn estimate of the amount of time spent in subroutines of @code{report}when @code{report} was called from @code{main}.The sum of the @code{self} and @code{children} fields is an estimateof the amount of time spent within calls to @code{report} from @code{main}.@item calledTwo numbers: the number of times @code{report} was called from @code{main},followed by the total number of non-recursive calls to @code{report} fromall its callers.@item name and index numberThe name of the caller of @code{report} to which this line applies,followed by the caller's index number.Not all functions have entries in the call graph; someoptions to @code{gprof} request the omission of certain functions.When a caller has no entry of its own, it still has caller-linesin the entries of the functions it calls.If the caller is part of a recursion cycle, the cycle number isprinted between the name and the index number.@end tableIf the identity of the callers of a function cannot be determined, adummy caller-line is printed which has @samp{<spontaneous>} as the``caller's name'' and all other fields blank. This can happen forsignal handlers.@c What if some calls have determinable callers' names but not all?@c FIXME - still relevant?@node Subroutines, Cycles, Callers, Call Graph@subsection Lines for a Function's SubroutinesA function's entry has a line for each of its subroutines---in otherwords, a line for each other function that it called. These lines'fields correspond to the fields of the primary line, but their meaningsare different because of the difference in context.For reference, we repeat two lines from the entry for the function@code{main}, the primary line and a line for a subroutine, togetherwith the heading line that shows the names of the fields:@smallexampleindex % time self children called name@dots{}[2] 100.0 0.00 0.05 1 main [2]0.00 0.05 1/1 report [3]@end smallexampleHere are the meanings of the fields in the subroutine-line for @code{main}calling @code{report}:@table @code@item selfAn estimate of the amount of time spent directly within @code{report}when @code{report} was called from @code{main}.@item childrenAn estimate of the amount of time spent in subroutines of @code{report}when @code{report} was called from @code{main}.The sum of the @code{self} and @code{children} fields is an estimateof the total time spent in calls to @code{report} from @code{main}.@item calledTwo numbers, the number of calls to @code{report} from @code{main}followed by the total number of non-recursive calls to @code{report}.This ratio is used to determine how much of @code{report}'s @code{self}and @code{children} time gets credited to @code{main}.@xref{Assumptions}.@item nameThe name of the subroutine of @code{main} to which this line applies,followed by the subroutine's index number.If the caller is part of a recursion cycle, the cycle number isprinted between the name and the index number.@end table@node Cycles,, Subroutines, Call Graph@subsection How Mutually Recursive Functions Are Described@cindex cycle@cindex recursion cycleThe graph may be complicated by the presence of @dfn{cycles ofrecursion} in the call graph. A cycle exists if a function callsanother function that (directly or indirectly) calls (or appears tocall) the original function. For example: if @code{a} calls @code{b},and @code{b} calls @code{a}, then @code{a} and @code{b} form a cycle.Whenever there are call paths both ways between a pair of functions, theybelong to the same cycle. If @code{a} and @code{b} call each other and@code{b} and @code{c} call each other, all three make one cycle. Note thateven if @code{b} only calls @code{a} if it was not called from @code{a},@code{gprof} cannot determine this, so @code{a} and @code{b} are stillconsidered a cycle.The cycles are numbered with consecutive integers. When a functionbelongs to a cycle, each time the function name appears in the call graphit is followed by @samp{<cycle @var{number}>}.The reason cycles matter is that they make the time values in the callgraph paradoxical. The ``time spent in children'' of @code{a} shouldinclude the time spent in its subroutine @code{b} and in @code{b}'ssubroutines---but one of @code{b}'s subroutines is @code{a}! How much of@code{a}'s time should be included in the children of @code{a}, when@code{a} is indirectly recursive?The way @code{gprof} resolves this paradox is by creating a single entryfor the cycle as a whole. The primary line of this entry describes thetotal time spent directly in the functions of the cycle. The``subroutines'' of the cycle are the individual functions of the cycle, andall other functions that were called directly by them. The ``callers'' ofthe cycle are the functions, outside the cycle, that called functions inthe cycle.Here is an example portion of a call graph which shows a cycle containingfunctions @code{a} and @code{b}. The cycle was entered by a call to@code{a} from @code{main}; both @code{a} and @code{b} called @code{c}.@smallexampleindex % time self children called name----------------------------------------1.77 0 1/1 main [2][3] 91.71 1.77 0 1+5 <cycle 1 as a whole> [3]1.02 0 3 b <cycle 1> [4]0.75 0 2 a <cycle 1> [5]----------------------------------------3 a <cycle 1> [5][4] 52.85 1.02 0 0 b <cycle 1> [4]2 a <cycle 1> [5]0 0 3/6 c [6]----------------------------------------1.77 0 1/1 main [2]2 b <cycle 1> [4][5] 38.86 0.75 0 1 a <cycle 1> [5]3 b <cycle 1> [4]0 0 3/6 c [6]----------------------------------------@end smallexample@noindent(The entire call graph for this program contains in addition an entry for@code{main}, which calls @code{a}, and an entry for @code{c}, with callers@code{a} and @code{b}.)@smallexampleindex % time self children called name<spontaneous>[1] 100.00 0 1.93 0 start [1]0.16 1.77 1/1 main [2]----------------------------------------0.16 1.77 1/1 start [1][2] 100.00 0.16 1.77 1 main [2]1.77 0 1/1 a <cycle 1> [5]----------------------------------------1.77 0 1/1 main [2][3] 91.71 1.77 0 1+5 <cycle 1 as a whole> [3]1.02 0 3 b <cycle 1> [4]0.75 0 2 a <cycle 1> [5]0 0 6/6 c [6]----------------------------------------3 a <cycle 1> [5][4] 52.85 1.02 0 0 b <cycle 1> [4]2 a <cycle 1> [5]0 0 3/6 c [6]----------------------------------------1.77 0 1/1 main [2]2 b <cycle 1> [4][5] 38.86 0.75 0 1 a <cycle 1> [5]3 b <cycle 1> [4]0 0 3/6 c [6]----------------------------------------0 0 3/6 b <cycle 1> [4]0 0 3/6 a <cycle 1> [5][6] 0.00 0 0 6 c [6]----------------------------------------@end smallexampleThe @code{self} field of the cycle's primary line is the total timespent in all the functions of the cycle. It equals the sum of the@code{self} fields for the individual functions in the cycle, foundin the entry in the subroutine lines for these functions.The @code{children} fields of the cycle's primary line and subroutine linescount only subroutines outside the cycle. Even though @code{a} calls@code{b}, the time spent in those calls to @code{b} is not counted in@code{a}'s @code{children} time. Thus, we do not encounter the problem ofwhat to do when the time in those calls to @code{b} includes indirectrecursive calls back to @code{a}.The @code{children} field of a caller-line in the cycle's entry estimatesthe amount of time spent @emph{in the whole cycle}, and its othersubroutines, on the times when that caller called a function in the cycle.The @code{calls} field in the primary line for the cycle has two numbers:first, the number of times functions in the cycle were called by functionsoutside the cycle; second, the number of times they were called byfunctions in the cycle (including times when a function in the cycle callsitself). This is a generalization of the usual split into non-recursive andrecursive calls.The @code{calls} field of a subroutine-line for a cycle member in thecycle's entry says how many time that function was called from functions inthe cycle. The total of all these is the second number in the primary line's@code{calls} field.In the individual entry for a function in a cycle, the other functions inthe same cycle can appear as subroutines and as callers. These lines showhow many times each function in the cycle called or was called from each otherfunction in the cycle. The @code{self} and @code{children} fields in theselines are blank because of the difficulty of defining meanings for themwhen recursion is going on.@node Line-by-line,Annotated Source,Call Graph,Output@section Line-by-line Profiling@code{gprof}'s @samp{-l} option causes the program to perform@dfn{line-by-line} profiling. In this mode, histogramsamples are assigned not to functions, but to individuallines of source code. The program usually must be compiledwith a @samp{-g} option, in addition to @samp{-pg}, in orderto generate debugging symbols for tracking source code lines.The flat profile is the most useful output tablein line-by-line mode.The call graph isn't as useful as normal, sincethe current version of @code{gprof} does not propagatecall graph arcs from source code lines to the enclosing function.The call graph does, however, show each line of codethat called each function, along with a count.Here is a section of @code{gprof}'s output, without line-by-line profiling.Note that @code{ct_init} accounted for four histogram hits, and13327 calls to @code{init_block}.@smallexampleFlat profile:Each sample counts as 0.01 seconds.% cumulative self self totaltime seconds seconds calls us/call us/call name30.77 0.13 0.04 6335 6.31 6.31 ct_initCall graph (explanation follows)granularity: each sample hit covers 4 byte(s) for 7.69% of 0.13 secondsindex % time self children called name0.00 0.00 1/13496 name_too_long0.00 0.00 40/13496 deflate0.00 0.00 128/13496 deflate_fast0.00 0.00 13327/13496 ct_init[7] 0.0 0.00 0.00 13496 init_block@end smallexampleNow let's look at some of @code{gprof}'s output from the same program run,this time with line-by-line profiling enabled. Note that @code{ct_init}'sfour histogram hits are broken down into four lines of source code - one hitoccurred on each of lines 349, 351, 382 and 385. In the call graph,note how@code{ct_init}'s 13327 calls to @code{init_block} are broken downinto one call from line 396, 3071 calls from line 384, 3730 callsfrom line 385, and 6525 calls from 387.@smallexampleFlat profile:Each sample counts as 0.01 seconds.% cumulative selftime seconds seconds calls name7.69 0.10 0.01 ct_init (trees.c:349)7.69 0.11 0.01 ct_init (trees.c:351)7.69 0.12 0.01 ct_init (trees.c:382)7.69 0.13 0.01 ct_init (trees.c:385)Call graph (explanation follows)granularity: each sample hit covers 4 byte(s) for 7.69% of 0.13 seconds% time self children called name0.00 0.00 1/13496 name_too_long (gzip.c:1440)0.00 0.00 1/13496 deflate (deflate.c:763)0.00 0.00 1/13496 ct_init (trees.c:396)0.00 0.00 2/13496 deflate (deflate.c:727)0.00 0.00 4/13496 deflate (deflate.c:686)0.00 0.00 5/13496 deflate (deflate.c:675)0.00 0.00 12/13496 deflate (deflate.c:679)0.00 0.00 16/13496 deflate (deflate.c:730)0.00 0.00 128/13496 deflate_fast (deflate.c:654)0.00 0.00 3071/13496 ct_init (trees.c:384)0.00 0.00 3730/13496 ct_init (trees.c:385)0.00 0.00 6525/13496 ct_init (trees.c:387)[6] 0.0 0.00 0.00 13496 init_block (trees.c:408)@end smallexample@node Annotated Source,,Line-by-line,Output@section The Annotated Source Listing@code{gprof}'s @samp{-A} option triggers an annotated source listing,which lists the program's source code, each function labeled with thenumber of times it was called. You may also need to specify the@samp{-I} option, if @code{gprof} can't find the source code files.Compiling with @samp{gcc @dots{} -g -pg -a} augments your programwith basic-block counting code, in addition to function counting code.This enables @code{gprof} to determine how many times each lineof code was executed.For example, consider the following function, taken from gzip,with line numbers added:@smallexample1 ulg updcrc(s, n)2 uch *s;3 unsigned n;4 @{5 register ulg c;67 static ulg crc = (ulg)0xffffffffL;89 if (s == NULL) @{10 c = 0xffffffffL;11 @} else @{12 c = crc;13 if (n) do @{14 c = crc_32_tab[...];15 @} while (--n);16 @}17 crc = c;18 return c ^ 0xffffffffL;19 @}@end smallexample@code{updcrc} has at least five basic-blocks.One is the function itself. The@code{if} statement on line 9 generates two more basic-blocks, onefor each branch of the @code{if}. A fourth basic-block results fromthe @code{if} on line 13, and the contents of the @code{do} loop formthe fifth basic-block. The compiler may also generate additionalbasic-blocks to handle various special cases.A program augmented for basic-block counting can be analyzed with@samp{gprof -l -A}. I also suggest use of the @samp{-x} option,which ensures that each line of code is labeled at least once.Here is @code{updcrc}'sannotated source listing for a sample @code{gzip} run:@smallexampleulg updcrc(s, n)uch *s;unsigned n;2 ->@{register ulg c;static ulg crc = (ulg)0xffffffffL;2 -> if (s == NULL) @{1 -> c = 0xffffffffL;1 -> @} else @{1 -> c = crc;1 -> if (n) do @{26312 -> c = crc_32_tab[...];26312,1,26311 -> @} while (--n);@}2 -> crc = c;2 -> return c ^ 0xffffffffL;2 ->@}@end smallexampleIn this example, the function was called twice, passing once througheach branch of the @code{if} statement. The body of the @code{do}loop was executed a total of 26312 times. Note how the @code{while}statement is annotated. It began execution 26312 times, once foreach iteration through the loop. One of those times (the last time)it exited, while it branched back to the beginning of the loop 26311 times.@node Inaccuracy@chapter Inaccuracy of @code{gprof} Output@menu* Sampling Error:: Statistical margins of error* Assumptions:: Estimating children times@end menu@node Sampling Error,Assumptions,,Inaccuracy@section Statistical Sampling ErrorThe run-time figures that @code{gprof} gives you are based on a samplingprocess, so they are subject to statistical inaccuracy. If a function runsonly a small amount of time, so that on the average the sampling processought to catch that function in the act only once, there is a pretty goodchance it will actually find that function zero times, or twice.By contrast, the number-of-calls and basic-block figuresare derived by counting, notsampling. They are completely accurate and will not vary from run to runif your program is deterministic.The @dfn{sampling period} that is printed at the beginning of the flatprofile says how often samples are taken. The rule of thumb is that arun-time figure is accurate if it is considerably bigger than the samplingperiod.The actual amount of error can be predicted.For @var{n} samples, the @emph{expected} erroris the square-root of @var{n}. For example,if the sampling period is 0.01 seconds and @code{foo}'s run-time is 1 second,@var{n} is 100 samples (1 second/0.01 seconds), sqrt(@var{n}) is 10 samples, sothe expected error in @code{foo}'s run-time is 0.1 seconds (10*0.01 seconds),or ten percent of the observed value.Again, if the sampling period is 0.01 seconds and @code{bar}'s run-time is100 seconds, @var{n} is 10000 samples, sqrt(@var{n}) is 100 samples, sothe expected error in @code{bar}'s run-time is 1 second,or one percent of the observed value.It is likely tovary this much @emph{on the average} from one profiling run to the next.(@emph{Sometimes} it will vary more.)This does not mean that a small run-time figure is devoid of information.If the program's @emph{total} run-time is large, a small run-time for onefunction does tell you that that function used an insignificant fraction ofthe whole program's time. Usually this means it is not worth optimizing.One way to get more accuracy is to give your program more (but similar)input data so it will take longer. Another way is to combine the data fromseveral runs, using the @samp{-s} option of @code{gprof}. Here is how:@enumerate@itemRun your program once.@itemIssue the command @samp{mv gmon.out gmon.sum}.@itemRun your program again, the same as before.@itemMerge the new data in @file{gmon.out} into @file{gmon.sum} with this command:@examplegprof -s @var{executable-file} gmon.out gmon.sum@end example@itemRepeat the last two steps as often as you wish.@itemAnalyze the cumulative data using this command:@examplegprof @var{executable-file} gmon.sum > @var{output-file}@end example@end enumerate@node Assumptions,,Sampling Error,Inaccuracy@section Estimating @code{children} TimesSome of the figures in the call graph are estimates---for example, the@code{children} time values and all the time figures in caller andsubroutine lines.There is no direct information about these measurements in the profiledata itself. Instead, @code{gprof} estimates them by making an assumptionabout your program that might or might not be true.The assumption made is that the average time spent in each call to anyfunction @code{foo} is not correlated with who called @code{foo}. If@code{foo} used 5 seconds in all, and 2/5 of the calls to @code{foo} camefrom @code{a}, then @code{foo} contributes 2 seconds to @code{a}'s@code{children} time, by assumption.This assumption is usually true enough, but for some programs it is farfrom true. Suppose that @code{foo} returns very quickly when its argumentis zero; suppose that @code{a} always passes zero as an argument, whileother callers of @code{foo} pass other arguments. In this program, all thetime spent in @code{foo} is in the calls from callers other than @code{a}.But @code{gprof} has no way of knowing this; it will blindly andincorrectly charge 2 seconds of time in @code{foo} to the children of@code{a}.@c FIXME - has this been fixed?We hope some day to put more complete data into @file{gmon.out}, so thatthis assumption is no longer needed, if we can figure out how. For thenonce, the estimated figures are usually more useful than misleading.@node How do I?@chapter Answers to Common Questions@table @asis@item How can I get more exact information about hot spots in my program?Looking at the per-line call counts only tells part of the story.Because @code{gprof} can only report call times and counts by function,the best way to get finer-grained information on where the programis spending its time is to re-factor large functions into sequencesof calls to smaller ones. Beware however that this can introduceartifical hot spots since compiling with @samp{-pg} adds a significantoverhead to function calls. An alternative solution is to use anon-intrusive profiler, e.g.@: oprofile.@item How do I find which lines in my program were executed the most times?Compile your program with basic-block counting enabled, run it, thenuse the following pipeline:@examplegprof -l -C @var{objfile} | sort -k 3 -n -r@end exampleThis listing will show you the lines in your code executed most often,but not necessarily those that consumed the most time.@item How do I find which lines in my program called a particular function?Use @samp{gprof -l} and lookup the function in the call graph.The callers will be broken down by function and line number.@item How do I analyze a program that runs for less than a second?Try using a shell script like this one:@examplefor i in `seq 1 100`; dofastprogmv gmon.out gmon.out.$idonegprof -s fastprog gmon.out.*gprof fastprog gmon.sum@end exampleIf your program is completely deterministic, all the call countswill be simple multiples of 100 (i.e. a function called once ineach run will appear with a call count of 100).@end table@node Incompatibilities@chapter Incompatibilities with Unix @code{gprof}@sc{gnu} @code{gprof} and Berkeley Unix @code{gprof} use the same datafile @file{gmon.out}, and provide essentially the same information. Butthere are a few differences.@itemize @bullet@item@sc{gnu} @code{gprof} uses a new, generalized file format with supportfor basic-block execution counts and non-realtime histograms. A magiccookie and version number allows @code{gprof} to easily identifynew style files. Old BSD-style files can still be read.@xref{File Format}.@itemFor a recursive function, Unix @code{gprof} lists the function as aparent and as a child, with a @code{calls} field that lists the numberof recursive calls. @sc{gnu} @code{gprof} omits these lines and putsthe number of recursive calls in the primary line.@itemWhen a function is suppressed from the call graph with @samp{-e}, @sc{gnu}@code{gprof} still lists it as a subroutine of functions that call it.@item@sc{gnu} @code{gprof} accepts the @samp{-k} with its argumentin the form @samp{from/to}, instead of @samp{from to}.@itemIn the annotated source listing,if there are multiple basic blocks on the same line,@sc{gnu} @code{gprof} prints all of their counts, separated by commas.@ignore - it does this now@itemThe function names printed in @sc{gnu} @code{gprof} output do not includethe leading underscores that are added internally to the front of allC identifiers on many operating systems.@end ignore@itemThe blurbs, field widths, and output formats are different. @sc{gnu}@code{gprof} prints blurbs after the tables, so that you can see thetables without skipping the blurbs.@end itemize@node Details@chapter Details of Profiling@menu* Implementation:: How a program collects profiling information* File Format:: Format of @samp{gmon.out} files* Internals:: @code{gprof}'s internal operation* Debugging:: Using @code{gprof}'s @samp{-d} option@end menu@node Implementation,File Format,,Details@section Implementation of ProfilingProfiling works by changing how every function in your program is compiledso that when it is called, it will stash away some information about whereit was called from. From this, the profiler can figure out what functioncalled it, and can count how many times it was called. This change is madeby the compiler when your program is compiled with the @samp{-pg} option,which causes every function to call @code{mcount}(or @code{_mcount}, or @code{__mcount}, depending on the OS and compiler)as one of its first operations.The @code{mcount} routine, included in the profiling library,is responsible for recording in an in-memory call graph tableboth its parent routine (the child) and its parent's parent. This istypically done by examining the stack frame to find boththe address of the child, and the return address in the original parent.Since this is a very machine-dependent operation, @code{mcount}itself is typically a short assembly-language stub routinethat extracts the requiredinformation, and then calls @code{__mcount_internal}(a normal C function) with two arguments - @code{frompc} and @code{selfpc}.@code{__mcount_internal} is responsible for maintainingthe in-memory call graph, which records @code{frompc}, @code{selfpc},and the number of times each of these call arcs was traversed.GCC Version 2 provides a magical function (@code{__builtin_return_address}),which allows a generic @code{mcount} function to extract therequired information from the stack frame. However, on somearchitectures, most notably the SPARC, using this builtin can bevery computationally expensive, and an assembly language versionof @code{mcount} is used for performance reasons.Number-of-calls information for library routines is collected by using aspecial version of the C library. The programs in it are the same as inthe usual C library, but they were compiled with @samp{-pg}. If youlink your program with @samp{gcc @dots{} -pg}, it automatically uses theprofiling version of the library.Profiling also involves watching your program as it runs, and keeping ahistogram of where the program counter happens to be every now and then.Typically the program counter is looked at around 100 times per second ofrun time, but the exact frequency may vary from system to system.This is done is one of two ways. Most UNIX-like operating systemsprovide a @code{profil()} system call, which registers a memoryarray with the kernel, along with a scalefactor that determines how the program's address space mapsinto the array.Typical scaling values cause every 2 to 8 bytes of address spaceto map into a single array slot.On every tick of the system clock(assuming the profiled program is running), the value of theprogram counter is examined and the corresponding slot inthe memory array is incremented. Since this is done in the kernel,which had to interrupt the process anyway to handle the clockinterrupt, very little additional system overhead is required.However, some operating systems, most notably Linux 2.0 (and earlier),do not provide a @code{profil()} system call. On such a system,arrangements are made for the kernel to periodically delivera signal to the process (typically via @code{setitimer()}),which then performs the same operation of examining theprogram counter and incrementing a slot in the memory array.Since this method requires a signal to be delivered touser space every time a sample is taken, it uses considerablymore overhead than kernel-based profiling. Also, due to theadded delay required to deliver the signal, this method isless accurate as well.A special startup routine allocates memory for the histogram andeither calls @code{profil()} or sets upa clock signal handler.This routine (@code{monstartup}) can be invoked in several ways.On Linux systems, a special profiling startup file @code{gcrt0.o},which invokes @code{monstartup} before @code{main},is used instead of the default @code{crt0.o}.Use of this special startup file is one of the effectsof using @samp{gcc @dots{} -pg} to link.On SPARC systems, no special startup files are used.Rather, the @code{mcount} routine, when it is invoked forthe first time (typically when @code{main} is called),calls @code{monstartup}.If the compiler's @samp{-a} option was used, basic-block countingis also enabled. Each object file is then compiled with a static arrayof counts, initially zero.In the executable code, every time a new basic-block begins(i.e. when an @code{if} statement appears), an extra instructionis inserted to increment the corresponding count in the array.At compile time, a paired array was constructed that recordedthe starting address of each basic-block. Taken together,the two arrays record the starting address of every basic-block,along with the number of times it was executed.The profiling library also includes a function (@code{mcleanup}) which istypically registered using @code{atexit()} to be called as theprogram exits, and is responsible for writing the file @file{gmon.out}.Profiling is turned off, various headers are output, and the histogramis written, followed by the call-graph arcs and the basic-block counts.The output from @code{gprof} gives no indication of parts of your program thatare limited by I/O or swapping bandwidth. This is because samples of theprogram counter are taken at fixed intervals of the program's run time.Therefore, thetime measurements in @code{gprof} output say nothing about time that yourprogram was not running. For example, a part of the program that createsso much data that it cannot all fit in physical memory at once may run veryslowly due to thrashing, but @code{gprof} will say it uses little time. Onthe other hand, sampling by run time has the advantage that the amount ofload due to other users won't directly affect the output you get.@node File Format,Internals,Implementation,Details@section Profiling Data File FormatThe old BSD-derived file format used for profile data does not contain amagic cookie that allows to check whether a data file really is a@code{gprof} file. Furthermore, it does not provide a version number, thusrendering changes to the file format almost impossible. @sc{gnu} @code{gprof}uses a new file format that provides these features. For backwardcompatibility, @sc{gnu} @code{gprof} continues to support the old BSD-derivedformat, but not all features are supported with it. For example,basic-block execution counts cannot be accommodated by the old fileformat.The new file format is defined in header file @file{gmon_out.h}. Itconsists of a header containing the magic cookie and a version number,as well as some spare bytes available for future extensions. All datain a profile data file is in the native format of the target for whichthe profile was collected. @sc{gnu} @code{gprof} adapts automaticallyto the byte-order in use.In the new file format, the header is followed by a sequence ofrecords. Currently, there are three different record types: histogramrecords, call-graph arc records, and basic-block execution countrecords. Each file can contain any number of each record type. Whenreading a file, @sc{gnu} @code{gprof} will ensure records of the same type arecompatible with each other and compute the union of all records. Forexample, for basic-block execution counts, the union is simply the sumof all execution counts for each basic-block.@subsection Histogram RecordsHistogram records consist of a header that is followed by an array ofbins. The header contains the text-segment range that the histogramspans, the size of the histogram in bytes (unlike in the old BSDformat, this does not include the size of the header), the rate of theprofiling clock, and the physical dimension that the bin countsrepresent after being scaled by the profiling clock rate. Thephysical dimension is specified in two parts: a long name of up to 15characters and a single character abbreviation. For example, ahistogram representing real-time would specify the long name as"seconds" and the abbreviation as "s". This feature is useful forarchitectures that support performance monitor hardware (which,fortunately, is becoming increasingly common). For example, under DECOSF/1, the "uprofile" command can be used to produce a histogram of,say, instruction cache misses. In this case, the dimension in thehistogram header could be set to "i-cache misses" and the abbreviationcould be set to "1" (because it is simply a count, not a physicaldimension). Also, the profiling rate would have to be set to 1 inthis case.Histogram bins are 16-bit numbers and each bin represent an equalamount of text-space. For example, if the text-segment is onethousand bytes long and if there are ten bins in the histogram, eachbin represents one hundred bytes.@subsection Call-Graph RecordsCall-graph records have a format that is identical to the one used inthe BSD-derived file format. It consists of an arc in the call graphand a count indicating the number of times the arc was traversedduring program execution. Arcs are specified by a pair of addresses:the first must be within caller's function and the second must bewithin the callee's function. When performing profiling at thefunction level, these addresses can point anywhere within therespective function. However, when profiling at the line-level, it isbetter if the addresses are as close to the call-site/entry-point aspossible. This will ensure that the line-level call-graph is able toidentify exactly which line of source code performed calls to afunction.@subsection Basic-Block Execution Count RecordsBasic-block execution count records consist of a header followed by asequence of address/count pairs. The header simply specifies thelength of the sequence. In an address/count pair, the addressidentifies a basic-block and the count specifies the number of timesthat basic-block was executed. Any address within the basic-address canbe used.@node Internals,Debugging,File Format,Details@section @code{gprof}'s Internal OperationLike most programs, @code{gprof} begins by processing its options.During this stage, it may building its symspec list(@code{sym_ids.c:sym_id_add}), ifoptions are specified which use symspecs.@code{gprof} maintains a single linked list of symspecs,which will eventually get turned into 12 symbol tables,organized into six include/exclude pairs - onepair each for the flat profile (INCL_FLAT/EXCL_FLAT),the call graph arcs (INCL_ARCS/EXCL_ARCS),printing in the call graph (INCL_GRAPH/EXCL_GRAPH),timing propagation in the call graph (INCL_TIME/EXCL_TIME),the annotated source listing (INCL_ANNO/EXCL_ANNO),and the execution count listing (INCL_EXEC/EXCL_EXEC).After option processing, @code{gprof} finishesbuilding the symspec list by adding all the symspecs in@code{default_excluded_list} to the exclude listsEXCL_TIME and EXCL_GRAPH, and if line-by-line profiling is specified,EXCL_FLAT as well.These default excludes are not added to EXCL_ANNO, EXCL_ARCS, and EXCL_EXEC.Next, the BFD library is called to open the object file,verify that it is an object file,and read its symbol table (@code{core.c:core_init}),using @code{bfd_canonicalize_symtab} after mallocingan appropriately sized array of symbols. At this point,function mappings are read (if the @samp{--file-ordering} optionhas been specified), and the core text space is read intomemory (if the @samp{-c} option was given).@code{gprof}'s own symbol table, an array of Sym structures,is now built.This is done in one of two ways, by one of two routines, dependingon whether line-by-line profiling (@samp{-l} option) has beenenabled.For normal profiling, the BFD canonical symbol table is scanned.For line-by-line profiling, everytext space address is examined, and a new symbol table entrygets created every time the line number changes.In either case, two passes are made through the symboltable - one to count the size of the symbol table required,and the other to actually read the symbols. In between thetwo passes, a single array of type @code{Sym} is created ofthe appropriate length.Finally, @code{symtab.c:symtab_finalize}is called to sort the symbol table and remove duplicate entries(entries with the same memory address).The symbol table must be a contiguous array for two reasons.First, the @code{qsort} library function (which sorts an array)will be used to sort the symbol table.Also, the symbol lookup routine (@code{symtab.c:sym_lookup}),which finds symbolsbased on memory address, uses a binary search algorithmwhich requires the symbol table to be a sorted array.Function symbols are indicated with an @code{is_func} flag.Line number symbols have no special flags set.Additionally, a symbol can have an @code{is_static} flagto indicate that it is a local symbol.With the symbol table read, the symspecs can now be translatedinto Syms (@code{sym_ids.c:sym_id_parse}). Remember that a singlesymspec can match multiple symbols.An array of symbol tables(@code{syms}) is created, each entry of which is a symbol tableof Syms to be included or excluded from a particular listing.The master symbol table and the symspecs are examined by nestedloops, and every symbol that matches a symspec is insertedinto the appropriate syms table. This is done twice, once tocount the size of each required symbol table, and again to buildthe tables, which have been malloced between passes.From now on, to determine whether a symbol is on an includeor exclude symspec list, @code{gprof} simply uses itsstandard symbol lookup routine on the appropriate tablein the @code{syms} array.Now the profile data file(s) themselves are read(@code{gmon_io.c:gmon_out_read}),first by checking for a new-style @samp{gmon.out} header,then assuming this is an old-style BSD @samp{gmon.out}if the magic number test failed.New-style histogram records are read by @code{hist.c:hist_read_rec}.For the first histogram record, allocate a memory array to holdall the bins, and read them in.When multiple profile data files (or files with multiple histogramrecords) are read, the starting address, ending address, numberof bins and sampling rate must match between the various histograms,or a fatal error will result.If everything matches, just sum the additional histograms intothe existing in-memory array.As each call graph record is read (@code{call_graph.c:cg_read_rec}),the parent and child addressesare matched to symbol table entries, and a call graph arc iscreated by @code{cg_arcs.c:arc_add}, unless the arc fails a symspeccheck against INCL_ARCS/EXCL_ARCS. As each arc is added,a linked list is maintained of the parent's child arcs, and of the child'sparent arcs.Both the child's call count and the arc's call count areincremented by the record's call count.Basic-block records are read (@code{basic_blocks.c:bb_read_rec}),but only if line-by-line profiling has been selected.Each basic-block address is matched to a corresponding linesymbol in the symbol table, and an entry made in the symbol'sbb_addr and bb_calls arrays. Again, if multiple basic-blockrecords are present for the same address, the call countsare cumulative.A gmon.sum file is dumped, if requested (@code{gmon_io.c:gmon_out_write}).If histograms were present in the data files, assign them to symbols(@code{hist.c:hist_assign_samples}) by iterating over all the samplebins and assigning them to symbols. Since the symbol tableis sorted in order of ascending memory addresses, we cansimple follow along in the symbol table as we make our passover the sample bins.This step includes a symspec check against INCL_FLAT/EXCL_FLAT.Depending on the histogramscale factor, a sample bin may span multiple symbols,in which case a fraction of the sample count is allocatedto each symbol, proportional to the degree of overlap.This effect is rare for normal profiling, but overlapsare more common during line-by-line profiling, and cancause each of two adjacent lines to be credited with halfa hit, for example.If call graph data is present, @code{cg_arcs.c:cg_assemble} is called.First, if @samp{-c} was specified, a machine-dependentroutine (@code{find_call}) scans through each symbol's machine code,looking for subroutine call instructions, and adding themto the call graph with a zero call count.A topological sort is performed by depth-first numberingall the symbols (@code{cg_dfn.c:cg_dfn}), so thatchildren are always numbered less than their parents,then making a array of pointers into the symbol table and sorting it intonumerical order, which is reverse topologicalorder (children appear before parents).Cycles are also detected at this point, all membersof which are assigned the same topological number.Two passes are now made through this sorted array of symbol pointers.The first pass, from end to beginning (parents to children),computes the fraction of child time to propagate to each parentand a print flag.The print flag reflects symspec handling of INCL_GRAPH/EXCL_GRAPH,with a parent's include or exclude (print or no print) propertybeing propagated to its children, unless they themselves explicitly appearin INCL_GRAPH or EXCL_GRAPH.A second pass, from beginning to end (children to parents) actuallypropagates the timings along the call graph, subjectto a check against INCL_TIME/EXCL_TIME.With the print flag, fractions, and timings now stored in the symbolstructures, the topological sort array is now discarded, and anew array of pointers is assembled, this time sorted by propagated time.Finally, print the various outputs the user requested, which is now fairlystraightforward. The call graph (@code{cg_print.c:cg_print}) andflat profile (@code{hist.c:hist_print}) are regurgitations of valuesalready computed. The annotated source listing(@code{basic_blocks.c:print_annotated_source}) uses basic-blockinformation, if present, to label each line of code with call counts,otherwise only the function call counts are presented.The function ordering code is marginally well documentedin the source code itself (@code{cg_print.c}). Basically,the functions with the most use and the most parents areplaced first, followed by other functions with the most use,followed by lower use functions, followed by unused functionsat the end.@node Debugging,,Internals,Details@subsection Debugging @code{gprof}If @code{gprof} was compiled with debugging enabled,the @samp{-d} option triggers debugging output(to stdout) which can be helpful in understanding its operation.The debugging number specified is interpreted as a sum of the followingoptions:@table @asis@item 2 - Topological sortMonitor depth-first numbering of symbols during call graph analysis@item 4 - CyclesShows symbols as they are identified as cycle heads@item 16 - TallyingAs the call graph arcs are read, show each arc and howthe total calls to each function are tallied@item 32 - Call graph arc sortingDetails sorting individual parents/children within each call graph entry@item 64 - Reading histogram and call graph recordsShows address ranges of histograms as they are read, and eachcall graph arc@item 128 - Symbol tableReading, classifying, and sorting the symbol table from the object file.For line-by-line profiling (@samp{-l} option), also shows line numbersbeing assigned to memory addresses.@item 256 - Static call graphTrace operation of @samp{-c} option@item 512 - Symbol table and arc table lookupsDetail operation of lookup routines@item 1024 - Call graph propagationShows how function times are propagated along the call graph@item 2048 - Basic-blocksShows basic-block records as they are read from profile data(only meaningful with @samp{-l} option)@item 4096 - SymspecsShows symspec-to-symbol pattern matching operation@item 8192 - Annotate sourceTracks operation of @samp{-A} option@end table@node GNU Free Documentation License@chapter GNU Free Documentation LicenseGNU Free Documentation LicenseVersion 1.1, March 2000Copyright (C) 2000 Free Software Foundation, Inc.51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USAEveryone is permitted to copy and distribute verbatim copiesof this license document, but changing it is not allowed.0. PREAMBLEThe purpose of this License is to make a manual, textbook, or otherwritten document "free" in the sense of freedom: to assure everyonethe effective freedom to copy and redistribute it, with or withoutmodifying it, either commercially or noncommercially. Secondarily,this License preserves for the author and publisher a way to getcredit for their work, while not being considered responsible formodifications made by others.This License is a kind of "copyleft", which means that derivativeworks of the document must themselves be free in the same sense. Itcomplements the GNU General Public License, which is a copyleftlicense designed for free software.We have designed this License in order to use it for manuals for freesoftware, because free software needs free documentation: a freeprogram should come with manuals providing the same freedoms that thesoftware does. But this License is not limited to software manuals;it can be used for any textual work, regardless of subject matter orwhether it is published as a printed book. We recommend this Licenseprincipally for works whose purpose is instruction or reference.1. APPLICABILITY AND DEFINITIONSThis License applies to any manual or other work that contains anotice placed by the copyright holder saying it can be distributedunder the terms of this License. The "Document", below, refers to anysuch manual or work. Any member of the public is a licensee, and isaddressed as "you".A "Modified Version" of the Document means any work containing theDocument or a portion of it, either copied verbatim, or withmodifications and/or translated into another language.A "Secondary Section" is a named appendix or a front-matter section ofthe Document that deals exclusively with the relationship of thepublishers or authors of the Document to the Document's overall subject(or to related matters) and contains nothing that could fall directlywithin that overall subject. (For example, if the Document is in part atextbook of mathematics, a Secondary Section may not explain anymathematics.) The relationship could be a matter of historicalconnection with the subject or with related matters, or of legal,commercial, philosophical, ethical or political position regardingthem.The "Invariant Sections" are certain Secondary Sections whose titlesare designated, as being those of Invariant Sections, in the noticethat says that the Document is released under this License.The "Cover Texts" are certain short passages of text that are listed,as Front-Cover Texts or Back-Cover Texts, in the notice that says thatthe Document is released under this License.A "Transparent" copy of the Document means a machine-readable copy,represented in a format whose specification is available to thegeneral public, whose contents can be viewed and edited directly andstraightforwardly with generic text editors or (for images composed ofpixels) generic paint programs or (for drawings) some widely availabledrawing editor, and that is suitable for input to text formatters orfor automatic translation to a variety of formats suitable for inputto text formatters. A copy made in an otherwise Transparent fileformat whose markup has been designed to thwart or discouragesubsequent modification by readers is not Transparent. A copy that isnot "Transparent" is called "Opaque".Examples of suitable formats for Transparent copies include plainASCII without markup, Texinfo input format, LaTeX input format, SGMLor XML using a publicly available DTD, and standard-conforming simpleHTML designed for human modification. Opaque formats includePostScript, PDF, proprietary formats that can be read and edited onlyby proprietary word processors, SGML or XML for which the DTD and/orprocessing tools are not generally available, and themachine-generated HTML produced by some word processors for outputpurposes only.The "Title Page" means, for a printed book, the title page itself,plus such following pages as are needed to hold, legibly, the materialthis License requires to appear in the title page. For works informats which do not have any title page as such, "Title Page" meansthe text near the most prominent appearance of the work's title,preceding the beginning of the body of the text.2. VERBATIM COPYINGYou may copy and distribute the Document in any medium, eithercommercially or noncommercially, provided that this License, thecopyright notices, and the license notice saying this License appliesto the Document are reproduced in all copies, and that you add no otherconditions whatsoever to those of this License. You may not usetechnical measures to obstruct or control the reading or furthercopying of the copies you make or distribute. However, you may acceptcompensation in exchange for copies. If you distribute a large enoughnumber of copies you must also follow the conditions in section 3.You may also lend copies, under the same conditions stated above, andyou may publicly display copies.3. COPYING IN QUANTITYIf you publish printed copies of the Document numbering more than 100,and the Document's license notice requires Cover Texts, you must enclosethe copies in covers that carry, clearly and legibly, all these CoverTexts: Front-Cover Texts on the front cover, and Back-Cover Texts onthe back cover. Both covers must also clearly and legibly identifyyou as the publisher of these copies. The front cover must presentthe full title with all words of the title equally prominent andvisible. You may add other material on the covers in addition.Copying with changes limited to the covers, as long as they preservethe title of the Document and satisfy these conditions, can be treatedas verbatim copying in other respects.If the required texts for either cover are too voluminous to fitlegibly, you should put the first ones listed (as many as fitreasonably) on the actual cover, and continue the rest onto adjacentpages.If you publish or distribute Opaque copies of the Document numberingmore than 100, you must either include a machine-readable Transparentcopy along with each Opaque copy, or state in or with each Opaque copya publicly-accessible computer-network location containing a completeTransparent copy of the Document, free of added material, which thegeneral network-using public has access to download anonymously at nocharge using public-standard network protocols. If you use the latteroption, you must take reasonably prudent steps, when you begindistribution of Opaque copies in quantity, to ensure that thisTransparent copy will remain thus accessible at the stated locationuntil at least one year after the last time you distribute an Opaquecopy (directly or through your agents or retailers) of that edition tothe public.It is requested, but not required, that you contact the authors of theDocument well before redistributing any large number of copies, to givethem a chance to provide you with an updated version of the Document.4. MODIFICATIONSYou may copy and distribute a Modified Version of the Document underthe conditions of sections 2 and 3 above, provided that you releasethe Modified Version under precisely this License, with the ModifiedVersion filling the role of the Document, thus licensing distributionand modification of the Modified Version to whoever possesses a copyof it. In addition, you must do these things in the Modified Version:A. Use in the Title Page (and on the covers, if any) a title distinctfrom that of the Document, and from those of previous versions(which should, if there were any, be listed in the History sectionof the Document). You may use the same title as a previous versionif the original publisher of that version gives permission.B. List on the Title Page, as authors, one or more persons or entitiesresponsible for authorship of the modifications in the ModifiedVersion, together with at least five of the principal authors of theDocument (all of its principal authors, if it has less than five).C. State on the Title page the name of the publisher of theModified Version, as the publisher.D. Preserve all the copyright notices of the Document.E. Add an appropriate copyright notice for your modificationsadjacent to the other copyright notices.F. Include, immediately after the copyright notices, a license noticegiving the public permission to use the Modified Version under theterms of this License, in the form shown in the Addendum below.G. Preserve in that license notice the full lists of Invariant Sectionsand required Cover Texts given in the Document's license notice.H. Include an unaltered copy of this License.I. Preserve the section entitled "History", and its title, and add toit an item stating at least the title, year, new authors, andpublisher of the Modified Version as given on the Title Page. Ifthere is no section entitled "History" in the Document, create onestating the title, year, authors, and publisher of the Document asgiven on its Title Page, then add an item describing the ModifiedVersion as stated in the previous sentence.J. Preserve the network location, if any, given in the Document forpublic access to a Transparent copy of the Document, and likewisethe network locations given in the Document for previous versionsit was based on. These may be placed in the "History" section.You may omit a network location for a work that was published atleast four years before the Document itself, or if the originalpublisher of the version it refers to gives permission.K. In any section entitled "Acknowledgements" or "Dedications",preserve the section's title, and preserve in the section all thesubstance and tone of each of the contributor acknowledgementsand/or dedications given therein.L. Preserve all the Invariant Sections of the Document,unaltered in their text and in their titles. Section numbersor the equivalent are not considered part of the section titles.M. Delete any section entitled "Endorsements". Such a sectionmay not be included in the Modified Version.N. Do not retitle any existing section as "Endorsements"or to conflict in title with any Invariant Section.If the Modified Version includes new front-matter sections orappendices that qualify as Secondary Sections and contain no materialcopied from the Document, you may at your option designate some or allof these sections as invariant. To do this, add their titles to thelist of Invariant Sections in the Modified Version's license notice.These titles must be distinct from any other section titles.You may add a section entitled "Endorsements", provided it containsnothing but endorsements of your Modified Version by variousparties--for example, statements of peer review or that the text hasbeen approved by an organization as the authoritative definition of astandard.You may add a passage of up to five words as a Front-Cover Text, and apassage of up to 25 words as a Back-Cover Text, to the end of the listof Cover Texts in the Modified Version. Only one passage ofFront-Cover Text and one of Back-Cover Text may be added by (orthrough arrangements made by) any one entity. If the Document alreadyincludes a cover text for the same cover, previously added by you orby arrangement made by the same entity you are acting on behalf of,you may not add another; but you may replace the old one, on explicitpermission from the previous publisher that added the old one.The author(s) and publisher(s) of the Document do not by this Licensegive permission to use their names for publicity for or to assert orimply endorsement of any Modified Version.5. COMBINING DOCUMENTSYou may combine the Document with other documents released under thisLicense, under the terms defined in section 4 above for modifiedversions, provided that you include in the combination all of theInvariant Sections of all of the original documents, unmodified, andlist them all as Invariant Sections of your combined work in itslicense notice.The combined work need only contain one copy of this License, andmultiple identical Invariant Sections may be replaced with a singlecopy. If there are multiple Invariant Sections with the same name butdifferent contents, make the title of each such section unique byadding at the end of it, in parentheses, the name of the originalauthor or publisher of that section if known, or else a unique number.Make the same adjustment to the section titles in the list ofInvariant Sections in the license notice of the combined work.In the combination, you must combine any sections entitled "History"in the various original documents, forming one section entitled"History"; likewise combine any sections entitled "Acknowledgements",and any sections entitled "Dedications". You must delete all sectionsentitled "Endorsements."6. COLLECTIONS OF DOCUMENTSYou may make a collection consisting of the Document and other documentsreleased under this License, and replace the individual copies of thisLicense in the various documents with a single copy that is included inthe collection, provided that you follow the rules of this License forverbatim copying of each of the documents in all other respects.You may extract a single document from such a collection, and distributeit individually under this License, provided you insert a copy of thisLicense into the extracted document, and follow this License in allother respects regarding verbatim copying of that document.7. AGGREGATION WITH INDEPENDENT WORKSA compilation of the Document or its derivatives with other separateand independent documents or works, in or on a volume of a storage ordistribution medium, does not as a whole count as a Modified Versionof the Document, provided no compilation copyright is claimed for thecompilation. Such a compilation is called an "aggregate", and thisLicense does not apply to the other self-contained works thus compiledwith the Document, on account of their being thus compiled, if theyare not themselves derivative works of the Document.If the Cover Text requirement of section 3 is applicable to thesecopies of the Document, then if the Document is less than one quarterof the entire aggregate, the Document's Cover Texts may be placed oncovers that surround only the Document within the aggregate.Otherwise they must appear on covers around the whole aggregate.8. TRANSLATIONTranslation is considered a kind of modification, so you maydistribute translations of the Document under the terms of section 4.Replacing Invariant Sections with translations requires specialpermission from their copyright holders, but you may includetranslations of some or all Invariant Sections in addition to theoriginal versions of these Invariant Sections. You may include atranslation of this License provided that you also include theoriginal English version of this License. In case of a disagreementbetween the translation and the original English version of thisLicense, the original English version will prevail.9. TERMINATIONYou may not copy, modify, sublicense, or distribute the Document exceptas expressly provided for under this License. Any other attempt tocopy, modify, sublicense or distribute the Document is void, and willautomatically terminate your rights under this License. However,parties who have received copies, or rights, from you under thisLicense will not have their licenses terminated so long as suchparties remain in full compliance.10. FUTURE REVISIONS OF THIS LICENSEThe Free Software Foundation may publish new, revised versionsof the GNU Free Documentation License from time to time. Such newversions will be similar in spirit to the present version, but maydiffer in detail to address new problems or concerns. Seehttp://www.gnu.org/copyleft/.Each version of the License is given a distinguishing version number.If the Document specifies that a particular numbered version of thisLicense "or any later version" applies to it, you have the option offollowing the terms and conditions either of that specified version orof any later version that has been published (not as a draft) by theFree Software Foundation. If the Document does not specify a versionnumber of this License, you may choose any version ever published (notas a draft) by the Free Software Foundation.ADDENDUM: How to use this License for your documentsTo use this License in a document you have written, include a copy ofthe License in the document and put the following copyright andlicense notices just after the title page:@smallexampleCopyright (c) YEAR YOUR NAME.Permission is granted to copy, distribute and/or modify this documentunder the terms of the GNU Free Documentation License, Version 1.1or any later version published by the Free Software Foundation;with the Invariant Sections being LIST THEIR TITLES, with theFront-Cover Texts being LIST, and with the Back-Cover Texts being LIST.A copy of the license is included in the section entitled "GNUFree Documentation License".@end smallexampleIf you have no Invariant Sections, write "with no Invariant Sections"instead of saying which ones are invariant. If you have noFront-Cover Texts, write "no Front-Cover Texts" instead of"Front-Cover Texts being LIST"; likewise for Back-Cover Texts.If your document contains nontrivial examples of program code, werecommend releasing these examples in parallel under your choice offree software license, such as the GNU General Public License,to permit their use in free software.@contents@byeNEEDS AN INDEX-T - "traditional BSD style": How is it different? Should thedifferences be documented?example flat file adds up to 100.01%...note: time estimates now only go out to one decimal place (0.0), wherethey used to extend two (78.67).