% This file is part of HINT % Copyright 2017-2024 Martin Ruckert, % Hochschule Muenchen, Lothstrasse 64, 80336 Muenchen % % Permission is hereby granted, free of charge, to any person obtaining a copy % of this software and associated documentation files (the "Software"), to deal % in the Software without restriction, including without limitation the rights % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell % copies of the Software, and to permit persons to whom the Software is % furnished to do so, subject to the following conditions: % % The above copyright notice and this permission notice shall be % included in all copies or substantial portions of the Software. % % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE % COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, % WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT % OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN % THE SOFTWARE. % % Except as contained in this notice, the name of the copyright holders shall % not be used in advertising or otherwise to promote the sale, use or other % dealings in this Software without prior written authorization from the % copyright holders. \input texprofilemac.tex %% defining how to display certain C identifiers @s int8_t int @s uint8_t int @s int16_t int @s uint16_t int @s uint32_t int @s int32_t int @s uint64_t int @s bool int @ \makeindex \maketoc \makecode %\makefigindex \titletrue \null \font\largetitlefont=cmssbx10 scaled\magstep4 \font\Largetitlefont=cmssbx10 at 40pt \font\hugetitlefont=cmssbx10 at 48pt \font\smalltitlefontit=cmbxti10 scaled\magstep3 \font\smalltitlefont=cmssbx10 scaled\magstep3 %halftitle \def\raggedleft{\leftskip=0pt plus 5em\parfillskip=0pt \spaceskip=.3333em \xspaceskip=0.5em \emergencystretch=1em\relax \hyphenpenalty=1000\exhyphenpenalty=1000\pretolerance=10000\linepenalty=5000 } \hbox{} \vskip 0pt plus 1fill { \baselineskip=60pt \hugetitlefont\hfill \TeX profile:\par \Largetitlefont\raggedleft Profiling \TeX\ Source Files\par } \vskip 0pt plus 5fill \eject % verso of half title \titletrue \null \vfill \eject % title \titletrue \hbox{} \vskip 0pt plus 1fill { \baselineskip=1cm\parindent=0pt {\largetitlefont\raggedright {\TeX}profile}\par \leftline{\smalltitlefont Version 1.0} \vskip 10pt plus 0.5fill \leftline{\smalltitlefont Profiling \TeX} \vskip-3pt \leftline{\smalltitlefont Source Files} \vskip 10pt plus 0.5fill \hskip 0pt plus 2fill{\it F\"ur Beatriz}\hskip 0pt plus 0.5fill\hbox{} \bigskip \vskip 10pt plus 3fill \raggedright\baselineskip=12pt {\bf MARTIN RUCKERT} \ {\it Munich University of Applied Sciences}\par \bigskip \leftline{First edition} \bigskip % \leftline{\bf Eigendruck im Selbstverlag} % \bigskip } \eject % verso of title % copyright page (ii) \titletrue \begingroup \figrm \parindent=0pt %\null {\raggedright\advance\rightskip 3.5pc The author has taken care in the preparation of this book, but makes no expressed or implied warranty of any kind and assumes no responsibility for errors or omissions. No liability is assumed for incidental or consequential damages in connection with or arising out of the use of the information or programs contained herein. \bigskip {\figtt\obeylines\obeyspaces\baselineskip=11pt Ruckert, Martin. Profiling \TeX\ Source Files Includes index. % ISBN XXX-XXXXXXX-X } \bigskip {\raggedright\advance\rightskip 3.5pc plus 35pt \def\:{\discretionary{}{}{}} The internet page {\tt http:\://hint.\:userweb.\:mwn.\:de/} may contain current information about this book, downloadable software, and news. \vfill Copyright $\copyright$ 2024 by Martin Ruckert \smallskip All rights reserved. Printed by Kindle Direct Publishing. This publication is protected by copyright, and permission must be obtained prior to any prohibited reproduction, storage in a~retrieval system, or transmission in any form or by any means, electronic, mechanical, photocopying, recording, or likewise. To obtain permission to use material from this work, please submit a written request to Martin Ruckert, Hochschule M\"unchen, Fakult\"at f\"ur Informatik und Mathematik, Lothstrasse 64, 80335 M\"unchen, Germany. \medskip {\tt martin.ruckert\:@@hm.edu} \medskip %ISBN-13: 979-854992684-4\par \medskip %First printing: August 2019\par \medskip %Last commit: \input lastcommit.tex \par } } \endgroup \frontmatter \plainsection{Preface} This program is a result not of need or necessity but of curiosity. Being used to have a profiler at my disposal whenever I write a program, I just wanted to know if a profiler for \TeX\ could be written and what it would tell me. So when I was considering what could be my contribution to the TUG 2024 conference in Prague, I thought ``How about writing a profiler for \TeX?'' So I started the project and completed it just in time for the conference. The following document describes how to use {\tt texprofile}---the program that displays the data gathered by {\tt texprof}---in a readable form. In a future version, this document will also contain a ``User Manual'' that contains just the information needed by the person who wants to find out how \TeX\ is spending its time when processing a document. Until then be brave and try to cope with all the extra information contained in the following document! \vskip 1cm \noindent {\it M\"unchen\hfil\break May 28, 2024 \hfill Martin Ruckert} \tableofcontent %\thefigindex \mainmatter \section{The |main| Program} The program presented here reads data collected by a run of {\tt texprof} and presents it in a readable way. The structure of the program is similar to a lot of \CEE\ programs: @p #include #include #include #include #include #include @@; @@; @@; int main(int argc, char *argv[]) { int i, k; @@; @@; @@; return 0; } @ \section{Reading the Input File} Let us start with the interesting stuff and read the input file. @= static char *input_file_name=NULL; static FILE *in=NULL; @ First we need to open the input file. If that is successful, we check that there is a ``file marker'': a special sequence of characters that we expect at the very beginning of the input file and at various other places in the file just to make sure we have a file that is really meant to be read by {\tt texprofile}. @d FILE_MARKER "TEX PROF" @= if (input_file_name==NULL) commandline_error("no input file given"); in = fopen(input_file_name,"rb"); if (in==NULL) { char *tmp=malloc(strlen(input_file_name)+7); if (tmp!=NULL) { strcpy(tmp,input_file_name); strcat(tmp,".tprof"); input_file_name=tmp; in = fopen(input_file_name,"rb"); } } if (in==NULL) error("Unable to open input file"); check_file_marker("The input file does not seem to contain TeX profile data"); @ After the initial file marker we read the whole file which is organized in four sections separated by file markers. @= @@; check_file_marker("Invalid size data"); @@; check_file_marker("Invalid file names"); @@; check_file_marker("Invalid macro names"); @@>@; check_file_marker("Invalid timing data"); fclose(in); @ Before we explain how to read the different sections, we define functions to read multi-byte numbers in big endian format. @= static uint8_t fget1(void) { unsigned char buf[1]; if (fread(buf,1,1,in)!=1) error("Unexpected end of input"); return (uint8_t)buf[0]; } static uint16_t fget2(void) { unsigned char buf[2]; if (fread(buf,1,2,in)!=2) error("Unexpected end of input"); return ((uint16_t)buf[0]<<8)+buf[1]; } static uint32_t fget4(void) { unsigned char buf[4]; if (fread(buf,1,4,in)!=4) error("Unexpected end of input"); return ((((((uint32_t)buf[0]<<8)+buf[1])<<8)+buf[2])<<8)+buf[3]; } @ \subsection{Reading the Size Data} Here are the variables for the size data and the code to read them. @= static unsigned int file_num, /*number of input files*/ file_name_num, /*number of byte needed for the file names*/ macro_num, /*number of macros defined*/ macro_name_num, /*number of byte needed for the macro names*/ stamp_num, /*number of time stamps*/ depth_num; /*maximum stack depth*/ @ @= file_num=fget2(); file_name_num=fget2(); stamp_num=fget4(); if (stamp_num==0) error("The input file contains no time samples"); macro_num=fget2(); macro_name_num=fget4(); depth_num=fget2(); @ We conclude the reading of size data by using these values to allocate properly sized arrays. @= @@; @ \subsection{Reading the File Names} The first section in the input file contains the full names of all \TeX input files processed by {\tt texprof}. We need arrays of pointers to the full file names and to the short file names and a character array to store the actual file names. @= static char **full_file_names, **file_names, *file_name_buffer; #define ALLOCATE(V,S) V = calloc(S,sizeof(*V));\ if (V==NULL)@+ error("Out of memory for " #V "[" #S "]"); @ @= ALLOCATE(full_file_names,file_num); ALLOCATE(file_names,file_num); ALLOCATE(file_name_buffer,file_name_num); @ The first three files are not ordinary files but are used for special purposes: File number 0 is used for tokens that {\tt texprof} can not associate with an input file. These are usually only the tokens that are loaded from a \TeX\ format files since format files produced by \TeX's \.{\\dump} primitive do not contain file and line information. File number 1 is used for the ``system'' file. Its ``line numbers'' identify not a ``line'' but the kind of action that was taken by the system. File number 2 is used for the ``terminal'' file. It is used for text that is entered either on the command line or in an interactive run of \TeX. @d unknown_file 0 /*unknown origin*/ @d system_file 1 /*generated by the system*/ @d terminal_file 2 /*read from the terminal*/ @d DIR_SEPARATOR '/' @= i=k=0; while (k< file_num) { char c; full_file_names[k]=file_names[k]=file_name_buffer+i; do { c = fget1(); if (i>=file_name_num) error("File name buffer overflow"); file_name_buffer[i++]=c; if (c==DIR_SEPARATOR) file_names[k]=file_name_buffer+i; } while (c!=0); k++; } @ \subsection{Reading the Macro Names} After the file names, we read the macro names and construct the |macro_map| table. It maps the multi-letter macro numbers from \TeX's hash table to the sequential numbering used to access the |macro_names| array. This map is used when reading the time stamps to map \TeX's control sequence numbers to the sequential numbers needed to access the macro names. After reading the time stamps, the |macro_map| array can be deallocated. @= static char *macro_name_buffer, **macro_names; static uint16_t *macro_stack; static struct map { uint16_t n; /* name */ uint16_t m; /*macro definition*/ } *macro_map; @ @= ALLOCATE(macro_names,macro_num); ALLOCATE(macro_name_buffer,macro_name_num); ALLOCATE(macro_map,undefined_control_sequence+every_eof_text+1); ALLOCATE(macro_stack,depth_num+1); @ @= i=0;k=0; while (k< macro_num) { int j; char c; j=fget2(); macro_map[j].n=k; macro_map[j].m=0; macro_names[k++]=macro_name_buffer+i; do { c=fget1(); if (i>=macro_name_num) error("Name buffer overflow"); macro_name_buffer[i++]=c; } while (c!=0); } for (i=1;i<=every_eof_text;i++) { macro_map[undefined_control_sequence+i].n=macro_num+i; macro_map[undefined_control_sequence+i].m=0; } @ To print a macro name, we use the function |print_cs|. Given a control sequence number |n|, it can be either from an active character, or from a single letter control sequence or from a multi-letter control sequence. If the number |n| comes from an active character, we get the character by subtracting |active_base|; If it comes comes from a single character control sequence, we get the character by subtracting |single_base|; if |n|is equal to |null_cs|, it comes from the empty control sequence; and if it comes from a multi-letter control sequence, |n| is already mapped to the macro name index plus |hash_base|. @d active_base 1 /*beginning of region 1, for active character equivalents*/ @d single_base (active_base+256) /*equivalents of one-character control sequences*/ @d null_cs (single_base+256) /*equivalent of \.{\\csname\\endcsname}*/ @d hash_base (null_cs+1) /*beginning of region 2, for the hash table*/ @d hash_size 45000 /*maximum number of control sequences; it should be at most about |(mem_max-mem_min)/(double)10|*/ @d frozen_control_sequence (hash_base+hash_size) /*for error recovery*/ @d frozen_null_font (frozen_control_sequence+11) /*permanent `\.{\\nullfont}'*/ @d undefined_control_sequence (frozen_null_font+257) /*dummy location*/ @d output_text 6 @d every_eof_text 15 @= void print_cs(int n) { if (n< hash_base) { if (n < single_base) { int c=n-active_base; if (c<0) printf("File"); else if (isprint(c)) printf("%c",c); else printf("0x%02x",c); } else if (n < null_cs) { int c=n-single_base; if (isprint(c)) printf("\\%c",c); else printf("\\0x%02x",c); } else printf("Empty"); } else if (n>=macro_num+hash_base) printf("\\%s",every_name[n-hash_base-macro_num-output_text]); else printf("\\%s",macro_names[n-hash_base]); } @ \subsection{Reading the Time Stamps} The last section contains the time stamps collected during the run of {\tt texprof}. The time stamps are stored for later processing in the |stamps| array. In addition to the timing data, the time stamps section contains information about macro calls. @= struct stamp { uint8_t c; /*command*/ uint8_t f; /*file*/ uint16_t l; /*line*/ uint16_t d; /*depth*/ uint16_t m; /*macro*/ uint32_t t; /*time*/ } *stamps; struct macro_def { uint16_t n; /* name */ uint8_t f; /*file*/ uint16_t l; /*line*/ uint16_t link; /* link to another |macro_def|*/ int a; /* number of concurrent activation records */ int count; /* number of calls */ uint16_t e; /* list of outgoing edges */ uint64_t t; /* time used for this macro */ uint64_t T; /* cumulative time spent in this macro */ uint64_t s; /* start time of first activation */ } *macro_defs; int macro_def_num; /*macros allocated*/ int macro_def_count; /*macros used*/ @ Since the |macro_defs| array will contain only those macros that actually occur in the timing data, it is hard to predict the size of the |macro_defs| array. So either a first pass over all the timing data or a dynamic array is needed. Here the decision was to use a dynamic array. @= ALLOCATE(stamps,stamp_num); macro_def_num=16; macro_def_count=1; /* zero element is a sentinel */ ALLOCATE(macro_defs,macro_def_num); @ @= #define REALLOC(A,C,N) \ { N=N*1.4142136+0.5; /* $\sqrt 2$ */\ A=realloc(A,N*sizeof(*A));\ if (A==NULL) error("Out of memory"); \ memset(A+C,0,(N-C)*sizeof(*A)); \ } int new_macro_def(void) { if (macro_def_count= int get_macro_def(int f, int l, int c) { int m = macro_map[c].m; if (m==0) { m=new_macro_def(); macro_map[c].m=m; } else { loop: if (macro_defs[m].f==f && macro_defs[m].l==l) return m; else if (macro_defs[m].link==0) { int n=new_macro_def(); macro_defs[m].link=n; m= n; } else { m= macro_defs[m].link; goto loop; } } if (c= bool opt_macro_id=false; @ @= case 'i': opt_macro_id=true;break; @ @= "-i add the macros file and line numbers after the macro name\n"@; @ @= void print_macro(int i) { print_cs(macro_defs[i].n); if (opt_macro_id) printf(" [%d,%d]",macro_defs[i].f,macro_defs[i].l); } @ Now we can read the time stamps and the changes to the macro stack. Each element of the timing data starts with a one byte command value which is followed by a variable number of data bytes. After the |system_macro_pop| command follows a two byte new stack depth. After all other commands follows a one byte file number and a two byte line number. The |system_macro_push| command is then followed by a two byte new stack depth and a two byte control sequence number. All remaining commands are followed by a four byte elapsed time in nano seconds. @= uint64_t total_time; /*sum of all command times*/ uint32_t total_num; /*number of all command times*/ uint64_t *file_time, *cmd_time; int *file_line; /* maximum line number/offsets per file */ int *cmd_freq; int cur_depth; @ @ @d POP_BIT 0x80 @= ALLOCATE(file_time,file_num); ALLOCATE(cmd_time,cmd_num); ALLOCATE(file_line,file_num+1); ALLOCATE(cmd_freq,cmd_num); cur_depth=-1; total_time=0; total_num=0; macro_defs[0].a=1; i=0; { uint8_t c = fget1(); /* the initial call */ @@; if (c!=system_macro_push) error("Timing data must start with an initial push command"); @