Debian Codegraph @

texk/web2c/texprofdir/texprofile.w

raw
1 % This file is part of HINT
2 % Copyright 2017-2024 Martin Ruckert,
3 % Hochschule Muenchen, Lothstrasse 64, 80336 Muenchen
4 %
5 % Permission is hereby granted, free of charge, to any person obtaining a copy
6 % of this software and associated documentation files (the "Software"), to deal
7 % in the Software without restriction, including without limitation the rights
8 % to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 % copies of the Software, and to permit persons to whom the Software is
10 % furnished to do so, subject to the following conditions:
11 %
12 % The above copyright notice and this permission notice shall be
13 % included in all copies or substantial portions of the Software.
14 %
15 % THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 % IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 % FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 % COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
19 % WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT
20 % OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21 % THE SOFTWARE.
22 %
23 % Except as contained in this notice, the name of the copyright holders shall
24 % not be used in advertising or otherwise to promote the sale, use or other
25 % dealings in this Software without prior written authorization from the
26 % copyright holders.
27
28 \input texprofilemac.tex
29
30 %% defining how to display certain C identifiers
31
32 @s int8_t int
33 @s uint8_t int
34 @s int16_t int
35 @s uint16_t int
36 @s uint32_t int
37 @s int32_t int
38 @s uint64_t int
39 @s bool int
40
41 @
42
43 \makeindex
44 \maketoc
45 \makecode
46 %\makefigindex
47 \titletrue
48
49 \null
50
51 \font\largetitlefont=cmssbx10 scaled\magstep4
52 \font\Largetitlefont=cmssbx10 at 40pt
53 \font\hugetitlefont=cmssbx10 at 48pt
54 \font\smalltitlefontit=cmbxti10 scaled\magstep3
55 \font\smalltitlefont=cmssbx10 scaled\magstep3
56
57 %halftitle
58 \def\raggedleft{\leftskip=0pt plus 5em\parfillskip=0pt
59 \spaceskip=.3333em \xspaceskip=0.5em \emergencystretch=1em\relax
60 \hyphenpenalty=1000\exhyphenpenalty=1000\pretolerance=10000\linepenalty=5000
61 }
62 \hbox{}
63 \vskip 0pt plus 1fill
64 { \baselineskip=60pt
65 \hugetitlefont\hfill \TeX profile:\par
66 \Largetitlefont\raggedleft Profiling \TeX\ Source Files\par
67 }
68 \vskip 0pt plus 5fill
69 \eject
70 % verso of half title
71 \titletrue
72 \null
73 \vfill
74 \eject
75
76 % title
77 \titletrue
78 \hbox{}
79 \vskip 0pt plus 1fill
80 {
81 \baselineskip=1cm\parindent=0pt
82 {\largetitlefont\raggedright {\TeX}profile}\par
83 \leftline{\smalltitlefont Version 1.0}
84 \vskip 10pt plus 0.5fill
85 \leftline{\smalltitlefont Profiling \TeX}
86 \vskip-3pt
87 \leftline{\smalltitlefont Source Files}
88 \vskip 10pt plus 0.5fill
89 \hskip 0pt plus 2fill{\it F\"ur Beatriz}\hskip 0pt plus 0.5fill\hbox{}
90 \bigskip
91 \vskip 10pt plus 3fill
92 \raggedright\baselineskip=12pt
93 {\bf MARTIN RUCKERT} \ {\it Munich University of Applied Sciences}\par
94 \bigskip
95 \leftline{First edition}
96 \bigskip
97 % \leftline{\bf Eigendruck im Selbstverlag}
98 % \bigskip
99 }
100 \eject
101
102 % verso of title
103 % copyright page (ii)
104 \titletrue
105 \begingroup
106 \figrm
107 \parindent=0pt
108 %\null
109 {\raggedright\advance\rightskip 3.5pc
110 The author has taken care in the preparation of this book,
111 but makes no expressed or implied warranty of any kind and assumes no
112 responsibility for errors or omissions. No liability is assumed for
113 incidental or consequential damages in connection with or arising out
114 of the use of the information or programs contained herein.
115
116 \bigskip
117 {\figtt\obeylines\obeyspaces\baselineskip=11pt
118 Ruckert, Martin.
119 Profiling \TeX\ Source Files
120 Includes index.
121 % ISBN XXX-XXXXXXX-X
122 }
123 \bigskip
124
125 {\raggedright\advance\rightskip 3.5pc plus 35pt
126 \def\:{\discretionary{}{}{}}
127 The internet page {\tt http:\://hint.\:userweb.\:mwn.\:de/}
128 may contain current information about this book, downloadable software,
129 and news.
130
131 \vfill
132 Copyright $\copyright$ 2024 by Martin Ruckert
133 \smallskip
134 All rights reserved.
135 Printed by Kindle Direct Publishing.
136 This publication is protected by copyright, and permission must be
137 obtained prior to any prohibited reproduction, storage in
138 a~retrieval system, or transmission in any form or by any means, electronic,
139 mechanical, photocopying, recording, or likewise.
140 To obtain permission to use material from this work, please submit a written
141 request to Martin Ruckert,
142 Hochschule M\"unchen,
143 Fakult\"at f\"ur Informatik und Mathematik,
144 Lothstrasse 64,
145 80335 M\"unchen,
146 Germany.
147 \medskip
148 {\tt martin.ruckert\:@@hm.edu}
149 \medskip
150 %ISBN-13: 979-854992684-4\par
151 \medskip
152 %First printing: August 2019\par
153 \medskip
154 %Last commit: \input lastcommit.tex
155 \par
156 }
157 }
158 \endgroup
159
160
161 \frontmatter
162
163
164
165 \plainsection{Preface}
166 This program is a result not of need or necessity but of curiosity.
167 Being used to have a profiler at my disposal whenever I write a program,
168 I just wanted to know if a profiler for \TeX\ could be written and what it would
169 tell me.
170 So when I was considering what could be my contribution to the TUG 2024 conference
171 in Prague, I thought ``How about writing a profiler for \TeX?''
172 So I started the project and completed it just in time for the conference.
173
174 The following document describes how to use {\tt texprofile}---the program that
175 displays the data gathered by {\tt texprof}---in a readable form.
176
177 In a future version, this document will also contain a ``User Manual''
178 that contains just the information needed by the person who wants to
179 find out how \TeX\ is spending its time when processing a document.
180 Until then be brave and try to cope with all the extra information
181 contained in the following document!
182
183 \vskip 1cm
184 \noindent {\it M\"unchen\hfil\break
185 May 28, 2024 \hfill Martin Ruckert}
186
187
188 \tableofcontent
189 %\thefigindex
190
191
192 \mainmatter
193 \section{The |main| Program}
194
195 The program presented here reads data collected by a run of {\tt texprof}
196 and presents it in a readable way.
197 The structure of the program is similar to a lot of \CEE\ programs:
198
199 @p #include <stdlib.h>
200 #include <stdio.h>
201 #include <stdint.h>
202 #include <stdbool.h>
203 #include <ctype.h>
204 #include <string.h>
205 @<declarations@>@;
206 @<error handling@>@;
207 @<functions@>@;
208
209 int main(int argc, char *argv[])
210 { int i, k;
211 @<process the command line@>@;
212 @<read the input file@>@;
213 @<write the output file@>@;
214 return 0;
215 }
216 @
217
218 \section{Reading the Input File}
219
220 Let us start with the interesting stuff and read the input file.
221 @<declarations@>=
222 static char *input_file_name=NULL;
223 static FILE *in=NULL;
224 @
225
226 First we need to open the input file. If that is successful, we check
227 that there is a ``file marker'': a special sequence of characters that we expect
228 at the very beginning of the input file and at various other places in the file just
229 to make sure we have a file that is really meant to be read by {\tt texprofile}.
230
231 @d FILE_MARKER "TEX PROF"
232
233 @<read the input file@>=
234 if (input_file_name==NULL)
235 commandline_error("no input file given");
236 in = fopen(input_file_name,"rb");
237 if (in==NULL)
238 { char *tmp=malloc(strlen(input_file_name)+7);
239 if (tmp!=NULL)
240 { strcpy(tmp,input_file_name);
241 strcat(tmp,".tprof");
242 input_file_name=tmp;
243 in = fopen(input_file_name,"rb");
244 }
245 }
246 if (in==NULL)
247 error("Unable to open input file");
248 check_file_marker("The input file does not seem to contain TeX profile data");
249 @
250
251 After the initial file marker we read the whole file which is
252 organized in four sections separated by file markers.
253
254 @<read the input file@>=
255 @<read size data@>@;
256 check_file_marker("Invalid size data");
257 @<read file names@>@;
258 check_file_marker("Invalid file names");
259 @<read macro names@>@;
260 check_file_marker("Invalid macro names");
261 @<read timing data@>@>@;
262 check_file_marker("Invalid timing data");
263 fclose(in);
264 @
265
266 Before we explain how to read the different sections, we define functions
267 to read multi-byte numbers in big endian format.
268
269 @<functions@>=
270 static uint8_t fget1(void)
271 { unsigned char buf[1];
272 if (fread(buf,1,1,in)!=1)
273 error("Unexpected end of input");
274 return (uint8_t)buf[0];
275 }
276
277 static uint16_t fget2(void)
278 { unsigned char buf[2];
279 if (fread(buf,1,2,in)!=2)
280 error("Unexpected end of input");
281 return ((uint16_t)buf[0]<<8)+buf[1];
282 }
283
284 static uint32_t fget4(void)
285 { unsigned char buf[4];
286 if (fread(buf,1,4,in)!=4)
287 error("Unexpected end of input");
288 return ((((((uint32_t)buf[0]<<8)+buf[1])<<8)+buf[2])<<8)+buf[3];
289 }
290 @
291
292 \subsection{Reading the Size Data}
293 Here are the variables for the size data and the code to read them.
294
295 @<declarations@>=
296 static unsigned int file_num, /*number of input files*/
297 file_name_num, /*number of byte needed for the file names*/
298 macro_num, /*number of macros defined*/
299 macro_name_num, /*number of byte needed for the macro names*/
300 stamp_num, /*number of time stamps*/
301 depth_num; /*maximum stack depth*/
302 @
303
304 @<read size data@>=
305 file_num=fget2();
306 file_name_num=fget2();
307 stamp_num=fget4();
308 if (stamp_num==0)
309 error("The input file contains no time samples");
310 macro_num=fget2();
311 macro_name_num=fget4();
312 depth_num=fget2();
313 @
314
315 We conclude the reading of size data by using these values to allocate
316 properly sized arrays.
317
318 @<read size data@>=
319 @<allocate arrays@>@;
320 @
321
322
323 \subsection{Reading the File Names}
324 The first section in the input file contains the full names of all
325 \TeX input files processed by {\tt texprof}.
326 We need arrays of pointers to the full file names and
327 to the short file names and a character array to store the actual file names.
328
329 @<declarations@>=
330 static char **full_file_names, **file_names, *file_name_buffer;
331 #define ALLOCATE(V,S) V = calloc(S,sizeof(*V));\
332 if (V==NULL)@+ error("Out of memory for " #V "[" #S "]");
333 @
334
335 @<allocate arrays@>=
336 ALLOCATE(full_file_names,file_num);
337 ALLOCATE(file_names,file_num);
338 ALLOCATE(file_name_buffer,file_name_num);
339 @
340
341
342 The first three files are not ordinary files but are used for special
343 purposes: File number 0 is used for tokens that {\tt texprof} can not
344 associate with an input file. These are usually only the tokens that
345 are loaded from a \TeX\ format files since format files produced by \TeX's
346 \.{\\dump} primitive do not contain file and line information.
347 File number 1 is used for the ``system'' file. Its ``line numbers'' identify
348 not a ``line'' but the kind of action that was taken by the system.
349 File number 2 is used for the ``terminal'' file. It is used for
350 text that is entered either on the command line or in an interactive run of \TeX.
351
352 @d unknown_file 0 /*unknown origin*/
353 @d system_file 1 /*generated by the system*/
354 @d terminal_file 2 /*read from the terminal*/
355 @d DIR_SEPARATOR '/'
356
357 @<read file names@>=
358 i=k=0;
359 while (k< file_num)
360 { char c;
361 full_file_names[k]=file_names[k]=file_name_buffer+i;
362 do { c = fget1();
363 if (i>=file_name_num) error("File name buffer overflow");
364 file_name_buffer[i++]=c;
365 if (c==DIR_SEPARATOR) file_names[k]=file_name_buffer+i;
366 } while (c!=0);
367 k++;
368 }
369 @
370
371
372 \subsection{Reading the Macro Names}
373 After the file names, we read the macro names and construct the
374 |macro_map| table. It maps the multi-letter macro numbers from \TeX's
375 hash table to the sequential numbering used to access the
376 |macro_names| array. This map is used when reading the time stamps to
377 map \TeX's control sequence numbers to the sequential numbers needed
378 to access the macro names. After reading the time stamps, the
379 |macro_map| array can be deallocated.
380
381 @<declarations@>=
382 static char *macro_name_buffer, **macro_names;
383 static uint16_t *macro_stack;
384 static struct map
385 { uint16_t n; /* name */
386 uint16_t m; /*macro definition*/
387 } *macro_map;
388 @
389
390 @<allocate arrays@>=
391 ALLOCATE(macro_names,macro_num);
392 ALLOCATE(macro_name_buffer,macro_name_num);
393 ALLOCATE(macro_map,undefined_control_sequence+every_eof_text+1);
394 ALLOCATE(macro_stack,depth_num+1);
395 @
396
397 @<read macro names@>=
398 i=0;k=0;
399 while (k< macro_num)
400 { int j;
401 char c;
402 j=fget2();
403 macro_map[j].n=k;
404 macro_map[j].m=0;
405 macro_names[k++]=macro_name_buffer+i;
406 do { c=fget1();
407 if (i>=macro_name_num) error("Name buffer overflow");
408 macro_name_buffer[i++]=c;
409 } while (c!=0);
410 }
411 for (i=1;i<=every_eof_text;i++)
412 { macro_map[undefined_control_sequence+i].n=macro_num+i;
413 macro_map[undefined_control_sequence+i].m=0;
414 }
415
416 @
417
418 To print a macro name, we use the function |print_cs|.
419 Given a control sequence number |n|,
420 it can be either from an active character, or from a
421 single letter control sequence or from a multi-letter
422 control sequence.
423 If the number |n| comes from an active character,
424 we get the character by subtracting |active_base|;
425 If it comes comes from a single character
426 control sequence, we get the character by subtracting
427 |single_base|; if |n|is equal to |null_cs|, it comes
428 from the empty control sequence; and if it comes
429 from a multi-letter control sequence, |n| is already
430 mapped to the macro name index plus |hash_base|.
431
432 @d active_base 1 /*beginning of region 1, for active character equivalents*/
433 @d single_base (active_base+256) /*equivalents of one-character control sequences*/
434 @d null_cs (single_base+256) /*equivalent of \.{\\csname\\endcsname}*/
435 @d hash_base (null_cs+1) /*beginning of region 2, for the hash table*/
436 @d hash_size 45000 /*maximum number of control sequences; it should be at most
437 about |(mem_max-mem_min)/(double)10|*/
438 @d frozen_control_sequence (hash_base+hash_size) /*for error recovery*/
439 @d frozen_null_font (frozen_control_sequence+11) /*permanent `\.{\\nullfont}'*/
440 @d undefined_control_sequence (frozen_null_font+257) /*dummy location*/
441 @d output_text 6
442 @d every_eof_text 15
443
444 @<functions@>=
445 void print_cs(int n)
446 { if (n< hash_base)
447 { if (n < single_base)
448 { int c=n-active_base;
449 if (c<0) printf("File");
450 else if (isprint(c)) printf("%c",c); else printf("0x%02x",c);
451 }
452 else if (n < null_cs)
453 { int c=n-single_base;
454 if (isprint(c)) printf("\\%c",c); else printf("\\0x%02x",c);
455 }
456 else printf("Empty");
457 }
458 else if (n>=macro_num+hash_base)
459 printf("\\%s",every_name[n-hash_base-macro_num-output_text]);
460 else
461 printf("\\%s",macro_names[n-hash_base]);
462 }
463 @
464
465
466 \subsection{Reading the Time Stamps}
467 The last section contains the time stamps collected during the run of
468 {\tt texprof}. The time stamps are stored for later processing in the
469 |stamps| array. In addition to the timing data, the time stamps
470 section contains information about macro calls.
471
472 @<declarations@>=
473 struct stamp {
474 uint8_t c; /*command*/
475 uint8_t f; /*file*/
476 uint16_t l; /*line*/
477 uint16_t d; /*depth*/
478 uint16_t m; /*macro*/
479 uint32_t t; /*time*/
480 } *stamps;
481
482 struct macro_def {
483 uint16_t n; /* name */
484 uint8_t f; /*file*/
485 uint16_t l; /*line*/
486 uint16_t link; /* link to another |macro_def|*/
487 int a; /* number of concurrent activation records */
488 int count; /* number of calls */
489 uint16_t e; /* list of outgoing edges */
490 uint64_t t; /* time used for this macro */
491 uint64_t T; /* cumulative time spent in this macro */
492 uint64_t s; /* start time of first activation */
493 } *macro_defs;
494
495 int macro_def_num; /*macros allocated*/
496 int macro_def_count; /*macros used*/
497 @
498
499 Since the |macro_defs| array will contain only those macros that
500 actually occur in the timing data, it is hard to predict the size
501 of the |macro_defs| array. So either a first pass over all the timing
502 data or a dynamic array is needed. Here the decision was to use
503 a dynamic array.
504
505 @<allocate arrays@>=
506 ALLOCATE(stamps,stamp_num);
507 macro_def_num=16;
508 macro_def_count=1; /* zero element is a sentinel */
509 ALLOCATE(macro_defs,macro_def_num);
510 @
511
512 @<functions@>=
513 #define REALLOC(A,C,N) \
514 { N=N*1.4142136+0.5; /* $\sqrt 2$ */\
515 A=realloc(A,N*sizeof(*A));\
516 if (A==NULL) error("Out of memory"); \
517 memset(A+C,0,(N-C)*sizeof(*A)); \
518 }
519
520 int new_macro_def(void)
521 { if (macro_def_count<macro_def_num)
522 return macro_def_count++;
523 REALLOC(macro_defs,macro_def_count,macro_def_num);
524 return macro_def_count++;
525 }
526 @
527
528 When reading the timing data, we will allocate for each new macro
529 call a new macro definition with its name and the file and line of
530 its definition. One problem to overcome here is that \TeX\ allocates
531 a macro name in the hash table only once for every name even if that
532 name is reused for various macros in different files or in different lines.
533 Here we need a unique number for each of these macros.
534 For simplification, however, we will use the same number if two
535 macros with the same name are defined in the same file and the same
536 line. If you need to distinguish these macros, move the definitions
537 to separate lines (or use different names because it will not only
538 confuse the profiler but also the readers of your program).
539
540 To convert the file, line, and control sequence number to
541 a unique macro definition number, we use the |macro_map| array
542 to store the macro definition number and link multiple macro
543 definitions that share the same name into a linked list
544 using the |link| field of the macro definition.
545
546 @<functions@>=
547 int get_macro_def(int f, int l, int c)
548 { int m = macro_map[c].m;
549 if (m==0)
550 { m=new_macro_def();
551 macro_map[c].m=m;
552 }
553 else
554 { loop:
555 if (macro_defs[m].f==f && macro_defs[m].l==l)
556 return m;
557 else if (macro_defs[m].link==0)
558 { int n=new_macro_def();
559 macro_defs[m].link=n;
560 m= n;
561 }
562 else
563 { m= macro_defs[m].link;
564 goto loop;
565 }
566 }
567 if (c<hash_base)
568 macro_defs[m].n=c;
569 else
570 macro_defs[m].n=hash_base+macro_map[c].n;
571 macro_defs[m].f=f;
572 macro_defs[m].l=l;
573 macro_defs[m].link=0;
574 return m;
575 }
576 @
577
578 To print a macro name we use the function |print_macro|. Because the name
579 will not uniquely identify a macro---\TeX\ allows using the same name for
580 different macros---there is an option to print the file and line number in
581 square brackets after the macro name.
582
583 @<declarations@>=
584 bool opt_macro_id=false;
585 @
586
587 @<process options@>=
588 case 'i': opt_macro_id=true;break;
589 @
590
591 @<explain format options@>=
592 "-i add the macros file and line numbers after the macro name\n"@;
593 @
594
595 @<functions@>=
596 void print_macro(int i)
597 { print_cs(macro_defs[i].n);
598 if (opt_macro_id) printf(" [%d,%d]",macro_defs[i].f,macro_defs[i].l);
599 }
600 @
601
602 Now we can read the time stamps and the changes to the macro stack.
603 Each element of the timing data starts with a one byte command value
604 which is followed by a variable number of data bytes.
605
606 After the |system_macro_pop| command follows a two byte
607 new stack depth.
608 After all other commands follows a one byte file number and a two byte
609 line number. The |system_macro_push| command is then followed
610 by a two byte new stack depth and a two byte control sequence number.
611 All remaining commands are followed by a four byte elapsed
612 time in nano seconds.
613
614 @<declarations@>=
615 uint64_t total_time; /*sum of all command times*/
616 uint32_t total_num; /*number of all command times*/
617 uint64_t *file_time, *cmd_time;
618 int *file_line; /* maximum line number/offsets per file */
619 int *cmd_freq;
620 int cur_depth;
621 @
622
623 @
624
625 @d POP_BIT 0x80
626
627 @<read timing data@>=
628 ALLOCATE(file_time,file_num);
629 ALLOCATE(cmd_time,cmd_num);
630 ALLOCATE(file_line,file_num+1);
631 ALLOCATE(cmd_freq,cmd_num);
632
633 cur_depth=-1;
634 total_time=0;
635 total_num=0;
636 macro_defs[0].a=1;
637 i=0;
638
639 { uint8_t c = fget1(); /* the initial call */
640 @<read a macro call@>@;
641 if (c!=system_macro_push)
642 error("Timing data must start with an initial push command");
643 @<time a push command@>@;
644 }
645 while (i<stamp_num)
646 { uint8_t c=fget1();
647 switch (c)
648 { case system_macro_pop_0: break;
649 case system_macro_pop_0+1:
650 case system_macro_pop_0+2:
651 case system_macro_pop_0+3:
652 case system_macro_pop_0+4:
653 case system_macro_pop_0+5:
654 case system_macro_pop_0+6:
655 case system_macro_pop_0+7:
656 case system_macro_pop_0+8:
657 case system_macro_pop_0+9:
658 case system_macro_pop_0+10:
659 { int d=c-system_macro_pop_0;
660 @<store pop |d|@>@;
661 break;
662 }
663 case system_macro_pop_small:
664 { int d=fget1();
665 @<store pop |d|@>@;
666 break;
667 }
668 case system_macro_pop:
669 { int d=fget2();
670 @<store pop |d|@>@;
671 break;
672 }
673 case system_macro_push:
674 { @<read a macro call@>@;
675 cur_depth++;
676 macro_stack[cur_depth]=m;
677 macro_defs[m].count++;
678 macro_defs[m].a++;
679 if (macro_defs[m].a==1)
680 { macro_defs[m].s=total_time;
681 }
682 start_child(macro_stack[cur_depth-1],m);
683 }
684 break;
685 default:
686 if (c&POP_BIT)
687 { int d=1;
688 @<store pop |d|@>@;
689 c=c&~POP_BIT;
690 }
691 { uint8_t f=fget1();
692 uint16_t l=fget2();
693 uint32_t t=fget4();
694 uint16_t m=macro_stack[cur_depth];
695 if (f>=file_num) error("File number out of range");
696 if (c>=cmd_num) error("Command number out of range");
697 stamps[i].c=c;
698 stamps[i].f=f;
699 if (l> file_line[f])
700 file_line[f]=l;
701 stamps[i].l=l;
702 stamps[i].t=t;
703 total_time+=t;
704 file_time[f]+=t;
705 macro_defs[m].t+=t;
706 cmd_time[c]+=t;
707 cmd_freq[c]++;
708 total_num++;
709 stamps[i].d=cur_depth;
710 stamps[i].m=m;
711 }
712 i++;
713 #ifdef DEBUG
714 printf("<%d:%d:%d> %s\n",i-1,c, cur_depth, cmd_name[c]);
715 #endif
716 break;
717 }
718 }
719 macro_defs[macro_stack[0]].T=total_time;
720 macro_defs[0].count=0;
721 macro_defs[0].T=0;
722 macro_defs[0].f=0;
723 macro_defs[0].l=0;
724
725
726 #ifdef DEBUG
727 printf("Finished reading %d commands, depth=%d\n",i,cur_depth);
728 #endif
729 @
730
731 The table of |cmd_name|s is defined in the appendix.
732
733 @<store pop |d|@>=
734 stamps[i].c=system_macro_pop;
735 stamps[i].d=cur_depth-d;
736 #ifdef DEBUG
737 printf("{%d:%d:%d>%d}\n",i,system_macro_pop,cur_depth+d,cur_depth);
738 #endif
739 @<time a pop command@>@;
740 i++;
741 @
742
743
744 @<read a macro call@>=
745 int f,l,n,m;
746 f=fget1();
747 l=fget2();
748 n=fget2();
749 m=get_macro_def(f, l, n);
750 stamps[i].c=system_macro_push;
751 stamps[i].f=f;
752 stamps[i].l=l;
753 stamps[i].d=cur_depth;
754 stamps[i].m=m;
755 #ifdef DEBUG
756 printf("[%d:%d<%d:",i,cur_depth, cur_depth+1);
757 print_macro(m);
758 printf("]\n");
759 #endif
760 i++;
761 @
762
763 \section{Writing the Output}
764 For simplicity and because it is often sufficient to have a
765 short look at the results, we send the output to the standard output stream.
766 Various tables of output can be selected using options on the command line.
767 For the selection of tables, we use uppercase letters like ``{\tt R}''; to modify the
768 presentation of the tables, we use lower case letters like ``{\tt s}'' or ``{\tt n}''.
769
770 \subsection{The Raw Time Stamps}
771 Let us start with some simple options: ``{\tt -R}'' will output
772 the raw time stamps. This is useful if the profiler runs for
773 a very short time or if a separate program wants to analyze the data.
774 In the long list of time stamps the file names
775 would only be distracting. So we print only the file numbers and
776 show the file names in a separate table (see below).
777 The option ``-s'' will show information about the macro stack along
778 with the time stamps and the option ``-n'' will show the serial numbers,
779 a feature that is mainly needed for debugging the {\tt texprofile} program.
780
781 @<declarations@>=
782 bool opt_raw=false;
783 bool opt_raw_stack=false;
784 bool opt_raw_num=false;
785 @
786
787 @<process options@>=
788 case 'R': opt_raw=true; break;
789 case 's': opt_raw_stack=true; break;
790 case 'n': opt_raw_num=true; break;
791 @
792
793 @<explain table options@>=
794 "-R show the table of raw time stamps\n"@;
795 @ @<explain format options@>=
796 "-s show the changes of the macro stack\n"@;
797 "-n show the time stamp numbers\n"@;
798 @
799
800 The following table shows the time in nano seconds,
801 the file number, the line number and the command executed.
802 Here and in the following tables, all fields are separated
803 by a TAB characters. So you can import the data in common
804 office products for further processing (see also the option {\tt -m} below).
805
806 @<show all time stamps if requested@>=
807 if (opt_raw)
808 { Mprintf("\nAll time stamps in order of appearance:\n");
809 if (opt_raw_num) Mprintf("number\t");
810 Mprintf("file\t line\ttime/ns\tcommand\t level\tmacro\n");
811 for (i=1;i<stamp_num;i++)
812 { int m=stamps[i].m;
813 @<extract |t|, |f|, |l|, and |c| from stamp |i|@>@;
814 if (c <= system_profile_off)
815 { if (opt_raw_num) printf("%6d\t",i);
816 print_fl(f,l);
817 printf("\t%7u\t%-23s\t%5d\t",t,CMD_NAME(c),stamps[i].d);
818 print_macro(m);
819 printf("\n");
820 }
821 else if (opt_raw_stack)
822 { if (opt_raw_num) printf("%6d\t",i);
823 printf("\t\t\t%-23s\t%5d\t",CMD_NAME(c),stamps[i].d);
824 if (c==system_macro_push)
825 print_macro(m);
826 printf("\n");
827 }
828 }
829 }
830 @
831
832
833
834
835
836 @<extract |t|, |f|, |l|, and |c| from stamp |i|@>=
837 uint32_t t=stamps[i].t;
838 uint16_t l=stamps[i].l;
839 uint8_t f=stamps[i].f;
840 uint8_t c=stamps[i].c;
841 @
842
843 \subsection{The Raw Macro Stack Changes}
844 Further we can display the raw macro stack changes.
845 @<declarations@>=
846 bool opt_stack=false;
847 @
848
849 @<process options@>=
850 case 'S': opt_stack=true; break;
851 @
852
853 @<explain table options@>=
854 "-S show the table of macro stack changes\n"@;
855 @
856
857 @<show the complete macro stack if requested@>=
858 if (opt_stack)
859 { int c,d,m;
860 Mprintf("\nThe macro stack and its nesting:\n"
861 "command\tdepth\tname [id]\n");
862 for(i=0;i<stamp_num;i++)
863 { c=stamps[i].c;
864 if (c<system_macro_push)
865 continue;
866 d=stamps[i].d;
867 m=stamps[i].m;
868 printf("%5d\t%s\t",d,CMD_NAME(c));
869 if (c==system_macro_push)
870 print_macro(m);
871 printf("\n");
872 }
873 }
874 @
875
876
877
878
879 \subsection{The Summary}
880 Now we can print print the totals for the \TeX\ run. Note that the option to
881 show the summary is on by default, but can be switched off with the
882 ``{\tt -N}'' command line switch.
883
884 @<declarations@>=
885 bool opt_summary=true;
886 @
887
888 @<process options@>=
889 case 'N': opt_summary=false;break;
890 @
891
892 @<explain table options@>=
893 "-N do not show the table of global information\n"@;
894 @
895
896
897 @<show the total time if requested@>=
898 if (opt_summary)
899 { printf("\n"
900 "Total time measured: %s\n", time_str(total_time));
901 printf("Total number of samples: %6d\n",total_num);
902 if (total_num>0)
903 printf("Average time per sample: %s\n",time_str(total_time/total_num));
904 printf("Total number of files: %5d\n",file_num);
905 printf("Total number of macros: %5d\n",macro_num);
906 printf("Maximum stack nesting depth: %5d\n",depth_num);
907 }
908 @
909
910 To print times over a wide range in a useful format,
911 we use the following function. The option ``{\tt -m}'' can be used
912 to display plain nano seconds which is the preferable if you plan
913 to import the data into another program for further processing.
914 The macro |Mprintf| is used instead of |printf| for lines that
915 should not be printed when |opt_machine| is true.
916
917 @<declarations@>=
918 bool opt_machine=false;
919 #define Mprintf(...) opt_machine?(void)0:printf(__VA_ARGS__)
920 @
921
922 @<process options@>=
923 case 'm': opt_machine=true;opt_summary=false;break;
924 @
925
926 @<explain format options@>=
927 "-m optimize output for machine readability\n"@;
928 @
929
930
931 @<functions@>=
932 char * time_str(double t)
933 { static char str[20];
934 if (opt_machine)
935 snprintf(str,20,"%12ld",(long)t);
936 else
937 { if (t<1000.0)
938 snprintf(str,20," %7.2f ns",t);
939 else if (t<1000000.0)
940 snprintf(str,20," %7.2f us",t/1000.0);
941 else if (t<1000000000.0)
942 snprintf(str,20," %7.2f ms",t/1000000.0);
943 else
944 snprintf(str,20," %7.2f s",t/1000000000.0);
945 }
946 return str;
947 }
948 @
949
950 We continue with a function to print file and line information in a readable way.
951
952
953 @<functions@>=
954 void print_fl(int f, int l)
955 { if (f==system_file && !opt_machine)
956 printf("system\t%7s",line_name[l]);
957 else
958 printf("%4d\t%5d",f,l);
959 }
960 @
961
962
963
964
965 \subsection{The File Summary}
966
967 @<declarations@>=
968 bool opt_files=false;
969 @
970
971 @<process options@>=
972 case 'F': opt_files=true; break;
973 @
974
975 @<explain table options@>=
976 "-F show all files\n"
977 @
978
979
980 Next we can print a summary table for the files:
981
982 @<show the file summary if requested@>=
983 if (opt_files)
984 { Mprintf("\nFiles in the order of appearance:\n");
985 Mprintf(" file\t lines\tpercent\t time"
986 "\tname\n");
987 for (i=0; i<file_num; i++)
988 { double p=(100.0*file_time[i])/total_time;
989 if (p>=percent_limit)
990 printf("%6d\t%6d\t%6.2f%%\t%s\t%s\n",
991 i, file_line[i],
992 p, time_str(file_time[i]),
993 full_file_names[i]);
994 }
995 }
996 @
997
998 \subsection{The Command Summary}
999 And similar for commands:
1000
1001 @<declarations@>=
1002 bool opt_cmd=false;
1003 @
1004
1005 @<process options@>=
1006 case 'C': opt_cmd=true;break;
1007 @
1008
1009 @<explain table options@>=
1010 "-C show table of command summaries\n"@;
1011 @
1012
1013
1014 @<show the command summary if requested@>=
1015 if (opt_cmd)
1016 { int *cmd_link=NULL;
1017 @<sort the commands by time@>@;
1018 Mprintf("\nCommand summary:\n");
1019 Mprintf(" cmd\t time\tpercent\t count\t average\tname\n");
1020 for (i=cmd_link[cmd_num]; i>=0; i=cmd_link[i])
1021 if (cmd_freq[i]>0)
1022 { printf("%4d\t%s\t%6.2f%%",
1023 i, time_str(cmd_time[i]),
1024 (100.0*cmd_time[i])/total_time);
1025 printf("\t%6d\t %s\t%s\n",
1026 cmd_freq[i],time_str(cmd_time[i]/cmd_freq[i]),
1027 CMD_NAME(i));
1028 }
1029 free(cmd_link);
1030 }
1031 @
1032
1033 To sort the commands in decreasing order of times,
1034 we allocate an array of links and sort the linked
1035 list using a simple insertion sort.
1036 We keep the links in |cmd_link| and the list head in
1037 |cmd_link[cmd_num]|. The end of the link is marked
1038 by $-1$.
1039
1040 @<sort the commands by time@>=
1041 ALLOCATE(cmd_link,cmd_num+1);
1042 cmd_link[cmd_num]=-1;
1043 for (i=0; i<cmd_num; i++)
1044 { int l=cmd_num;
1045 uint32_t t=cmd_time[i];
1046 while (cmd_link[l]>=0 && cmd_time[cmd_link[l]]>t)
1047 l=cmd_link[l];
1048 cmd_link[i]=cmd_link[l];
1049 cmd_link[l]=i;
1050 }
1051 @
1052
1053 \subsection{The Macro Summary}
1054 Here is a table of all macros called. It should be possible to sort
1055 this table by either the direct time or be the cumulative
1056 time. Further there should be an option to switch between absolute
1057 times and relative times as a percentage of the total time.
1058
1059 @<declarations@>=
1060 bool opt_macro=false;
1061 @
1062
1063 @<process options@>=
1064 case 'M': opt_macro=true;break;
1065 @
1066
1067 @<explain table options@>=
1068 "-M show the table of all macros called\n"@;
1069 @
1070
1071 To compute the macro summary, we traverse the time stamps while reading.
1072
1073 If there is a push command we do this:
1074 @<time a push command@>=
1075 cur_depth++;
1076 macro_stack[cur_depth]=m;
1077 macro_defs[m].count++;
1078 macro_defs[m].a++;
1079 if (macro_defs[m].a==1)
1080 { macro_defs[m].s=total_time;
1081 }
1082 @
1083
1084 If there is a pop command we do this:
1085
1086 @<time a pop command@>=
1087 while (cur_depth>stamps[i].d)
1088 { int m=macro_stack[cur_depth];
1089 if (macro_defs[m].a==1)
1090 macro_defs[m].T+=total_time-macro_defs[m].s;
1091 end_child(macro_stack[cur_depth-1],m);
1092 macro_defs[m].a--;
1093 cur_depth--;
1094 }
1095
1096 @
1097
1098 @<show the table of macros profiled if requested@>=
1099 if (opt_macro)
1100 { sort_macros();
1101 Mprintf("\nMacros profiled:\n");
1102 Mprintf(" file\t line\tcalls\t time direct\t cumulative\tname\n");
1103 i=0;
1104 do
1105 { printf("%5d\t%5d\t",macro_defs[i].f,macro_defs[i].l);
1106 printf("%5d\t%s",macro_defs[i].count, time_str(macro_defs[i].t));
1107 printf("\t%s\t",time_str(macro_defs[i].T));
1108 print_macro(i);
1109 printf("\n");
1110 i=macro_defs[i].link;
1111 } while (i!=0);
1112 }
1113 @
1114
1115 To sort the edges by their cumulative time, we use a simple insertion sort.
1116 We use |edges[0]| as the head of a new list and insert the list of edges
1117 starting at |macro_defs[i].e|. While we do this we keep the estimates for
1118 the cumulative time of the edges that we have to compute anyway.
1119
1120 @<functions@>=
1121 void sort_edges(uint16_t p)
1122 { int i,j,k;
1123 edges[0].sibling=0; /*head node becomes the empty list*/
1124 i=macro_defs[p].e;
1125 while (i!=0)
1126 { uint64_t Ti=edges[i].T;
1127 k=0;
1128 while ((j=edges[k].sibling)!=0)
1129 { uint64_t Tj=edges[j].T;
1130 if (Ti<Tj)
1131 k=j;
1132 else
1133 break;
1134 }
1135 edges[k].sibling=i;
1136 k=i;
1137 i=edges[i].sibling;
1138 edges[k].sibling=j;
1139 }
1140 macro_defs[p].e=edges[0].sibling;
1141 }
1142 @
1143
1144 @ To sort the macros, we use again an insertion sort. So the procedure is
1145 similar to the one we have just seen.
1146 The value 0 is used as a sentinel
1147 and |macro_defs[0].link| is used as the list head.
1148
1149
1150 @<functions@>=
1151 void sort_macros(void)
1152 { int i, k, j;
1153 static bool sorted=false;
1154 if (sorted) return;
1155 macro_defs[0].link=0;
1156 sort_edges(0);
1157 for (i=1;i<macro_def_count;i++)
1158 { uint64_t Ti=macro_defs[i].T;
1159 k=0;
1160 while ((j=macro_defs[k].link)!=0)
1161 { uint64_t Tj=macro_defs[j].T;
1162 if (Ti<Tj)
1163 k=j;
1164 else
1165 break;
1166 }
1167 macro_defs[i].link=j;
1168 macro_defs[k].link=i;
1169 sort_edges(i);
1170 }
1171 sorted=true;
1172 }
1173 @
1174
1175
1176
1177 \subsection{Cumulative Information for Lines}
1178 On the second pass over the time samples, we collect line based
1179 information. To store this information, we allocate a big array
1180 |total_line_time| containing the information for all lines and all
1181 files. To access a specific line, we convert the |file_line| array
1182 into an array of offsets for each file and add to it the line number.
1183
1184 @<declarations@>=
1185 int line_num=0;
1186 @
1187
1188 @<turn |file_line| into an array of offsets
1189 and compute the total number of lines@>=
1190 line_num=0;
1191 for (i=0;i<file_num;i++)
1192 { int fl= file_line[i];
1193 file_line[i]=line_num;
1194 line_num=line_num+fl+1;
1195 }
1196 file_line[file_num]=line_num;
1197 @
1198
1199 Now we are ready to compute the total time per line and the line
1200 frequency. For the frequency counts, we count any consecutive sequence
1201 of samples from the same file and line as one use of this line. So
1202 using multiple macros from the same line without intervening code from
1203 other lines will count only as a single access.
1204
1205 We need the following arrays:
1206 @<declarations@>=
1207 static uint64_t *line_time=NULL;
1208 static int *line_freq=NULL;
1209 @
1210
1211 The following function allocates the dynamic arrays just declared and
1212 fills them with content. Before doing so it checks that the arrays are
1213 not yet allocated because this would imply that the function was
1214 already called and there is nothing left to do. The information
1215 collected here is required for both, the |opt_lines| and the
1216 |opt_top_ten| tables, but there is no need to compute it twice.
1217
1218 @<functions@>=
1219 void collect_line_time(void)
1220 { int i, cur_f=-1,cur_l=-1;
1221 if (line_time!=NULL) return; /*don't run a second time*/
1222 @<turn |file_line| into an array of offsets
1223 and compute the total number of lines@>@;
1224 ALLOCATE(line_time,line_num);
1225 ALLOCATE(line_freq,line_num);
1226 for (i=0; i<stamp_num; i++)
1227 { @<extract |t|, |f|, |l|, and |c| from stamp |i|@>@;
1228 if (c<=system_profile_off)
1229 { line_time[file_line[f]+l]+=t;
1230 if (cur_f!=f || cur_l!=l)
1231 { line_freq[file_line[f]+l]++;
1232 cur_f=f; cur_l=l;
1233 }
1234 }
1235 }
1236 }
1237 @
1238
1239 Printing all lines with their time is usually not required.
1240 We want only those lines that have a contribution that is above
1241 a certain limit given as the percentage of total time.
1242
1243 @<declarations@>=
1244 double percent_limit=1.0;
1245 bool opt_lines=false;
1246 @
1247
1248 @<process options@>=
1249 case 'L': opt_lines=true; break;
1250 case 'p':{ char *endptr;
1251 percent_limit=strtod(option+1, &endptr);
1252 if (endptr==option+1)
1253 commandline_error("-p<n> without a numeric argument <n>");
1254 else
1255 option=endptr-1;
1256 }
1257 break;
1258 @
1259
1260 @<explain table options@>=
1261 "-L show the table of times per input line\n"@;
1262 @ @<explain format options@>=
1263 "-p<n> don't show information for items with cumulative time below <n> percent\n"@;
1264 @
1265
1266
1267 @<show lines above limit if requested@>=
1268 if (opt_lines)
1269 { uint64_t limit= total_time*percent_limit/100.0;
1270 int k;
1271 collect_line_time();
1272 Mprintf("\nLine summary:\n");
1273 if (percent_limit>0)
1274 Mprintf("Only files and lines above %.2f%%:\n",percent_limit);
1275 for (k=i=0; i<file_num; i++)
1276 { if (file_time[i]<=limit)
1277 k=file_line[i+1];
1278 else
1279 { printf("%s\n",file_names[i]);
1280 printf(" file\t line\tpercent\t time"
1281 "\t count\t average\n");
1282 printf("%6d\t\t%6.2f%%\t%s\n",
1283 i, (100.0*file_time[i])/total_time,time_str(file_time[i]));
1284
1285 for (;k<file_line[i+1]; k++)
1286 { uint64_t t=line_time[k];
1287 if (line_freq[k]>0 && t>=limit)
1288 { if (i==system_file)
1289 printf("\t%7s",line_name[k-file_line[i]]);
1290 else
1291 printf("\t%6d", k-file_line[i]);
1292 printf("\t%6.2f%%\t%s",
1293 100.0*t/total_time,time_str(t));
1294 printf("\t%6d\t%s",line_freq[k],time_str(t/line_freq[k]));
1295 printf("\n");
1296 }
1297 }
1298 printf("\n");
1299 }
1300 }
1301 }
1302 @
1303
1304 \subsection{Finding the ``Top Ten'' Lines}
1305 Now that we have for each line in one of the input files the total
1306 time used by it, we can sort the lines by their time use. It is
1307 neither efficient nor useful to sort all the lines, but it sufficient
1308 to find the ``top ten''.
1309
1310 @<declarations@>=
1311 static uint64_t *tt_time;
1312 static int *tt_file, *tt_line;
1313 static int tt=10+1, tt_count;;
1314 bool opt_top_ten;
1315 @
1316
1317 @<process options@>=
1318 case 'T': opt_top_ten=true;break;
1319 case 't': { char *endptr;
1320 tt=strtol(option+1, &endptr,10)+1;
1321 if (endptr==option+1)
1322 commandline_error("-t<n> without a numeric argument <n>");
1323 else if (tt<2 || tt>101)
1324 commandline_error("-t<n> with <n> out of bounds");
1325 option=endptr-1;
1326 }
1327 break;
1328 @
1329
1330 @<explain table options@>=
1331 "-T show the table of the top 10 input lines\n"@;
1332 @ @<explain format options@>=
1333 "-t<n> replace 10 by n (2<=n<=100, default 10) for the top 10 input lines\n"@;
1334 @
1335
1336
1337 @<find the top ten lines@>=
1338 ALLOCATE(tt_time,tt);
1339 ALLOCATE(tt_file,tt);
1340 ALLOCATE(tt_line,tt);
1341 tt_time[0]=0xFFFFFFFFFFFFFFFF;
1342 tt_file[0]=0;
1343 tt_line[0]=0;
1344 tt_time[1]=0;
1345 tt_file[1]=0;
1346 tt_line[1]=0;
1347 tt_count=2;
1348 { int f,l;
1349 for (f=l=0; f< file_num; f++)
1350 { for (;l<file_line[f+1]; l++)
1351 { uint32_t t=line_time[l];
1352 if (t>tt_time[tt_count-1])
1353 @<insert |t| into the top ten list@>@;
1354 }
1355 }
1356 }
1357 @
1358
1359 Inserting a new time into the top ten array using insertion sort.
1360
1361 @<insert |t| into the top ten list@>=
1362 {
1363 if (tt_count<tt)tt_count++;
1364 i= tt_count-1;
1365 while (tt_time[i-1]<t)
1366 { i--;
1367 tt_time[i+1]=tt_time[i];
1368 tt_file[i+1]=tt_file[i];
1369 tt_line[i+1]=tt_line[i];
1370 }
1371 tt_time[i]=t;
1372 tt_file[i]=f;
1373 tt_line[i]=l-file_line[f];
1374 }
1375 @
1376
1377 @<show the top ten lines@>=
1378 if (opt_top_ten)
1379 { collect_line_time();
1380 @<find the top ten lines@>@;
1381 Mprintf("\nThe top ten lines:\n");
1382 Mprintf(" file\t line\tpercent\t absolute"
1383 "\t count\t average\tfile\n");
1384 for (i=1; i< tt_count; i++)
1385 { int freq=line_freq[tt_line[i]+file_line[tt_file[i]]];
1386 uint32_t t =tt_time[i];
1387 if (t>0 && freq>0)
1388 { print_fl(tt_file[i],tt_line[i]);
1389 printf("\t%6.2f%%\t%s", 100.0*t/total_time,time_str(t));
1390 printf("\t%6d\t%s\t%s\n",freq, time_str(t/freq), file_names[tt_file[i]]);
1391 }
1392 }
1393 }
1394 @
1395
1396
1397 \subsection{The Call Graph}
1398 For each macro, we know already how often it was called, the
1399 cumulative time, and the time directly spent in the macro. For the
1400 call graph, we want to know for each macro which child macros it did
1401 call, how often it did call each child, how much this child
1402 contributed directly and cumulative to the macro.
1403 From this data we could derive which parent macros
1404 called it, how often it was called by each parent, and how much time
1405 it contributed directly and cumulatively to the parent.
1406 We need to form linked lists of edges, so
1407 each edge has a link to its siblings.
1408
1409 Following the conventions of {\tt gprof}, call counts are
1410 displayed in the format $n/m$ where $n$ is the number of calls on the
1411 edge of the call graph under consideration and $m$ is the total number
1412 of calls.
1413
1414 The table of macro definitions is already available, so what we need
1415 is just a collection of the edges with counts, direct times and
1416 cumulative times. It is possible to estimate direct and
1417 cumulative times from the counts and the timing information we have
1418 already for each macro, but this method is not very precise.
1419
1420 Since macro calls can form recursive loops, the parent is not only
1421 an ancestor of the child, the child may also be an ancestor of the parent
1422 and its siblings. (Sounds horrible, but we are talking about macro calls.)
1423 Therefore the cumulative time spent in executing a child macro
1424 might include time spent in the parent macro or in its sibling macros.
1425 Therefore we need to split the cumulative time spent in a macro into
1426 two components: The cumulative time |T| that can be attributed to this macro alone,
1427 and the time that is spent in this macro but is attributed to the
1428 parent or a sibling. The call the later time the ``loop time'' |L|.
1429 To compute |T| and |L|, we keep track of the activation count |a|
1430 of each child, and keep two auxiliary variables |ts| and |Ts| when
1431 we push the first activation record, and update |T| and |L| only
1432 when we pop the last activation of the macro.
1433 The variable |ts| is used to record the |total_time|
1434 and |Ts| is used to record the sum of the time directly attributed to the parent
1435 and the cumulative times attributed to all siblings.
1436 Recomputing these values when we pop the final activation,
1437 we can obtain the time |dt| passed since its first activation,
1438 and the time |dT| attributed to parent and siblings since then.
1439 We use |dT| to update |L| and |dt-dT| to update |T|.
1440
1441 Here is the declaration of an |edge|:
1442 @<declarations@>=
1443 struct edge {
1444 uint16_t child, sibling;
1445 int count, a;
1446 uint64_t T, L, ts, Ts;
1447 } *edges;
1448 int edges_count, edges_num;
1449 @
1450
1451 The total number of outgoing and incoming edges can only be estimated.
1452 So a dynamic allocation is used.
1453
1454 @<allocate arrays@>=
1455 edges_num=1024;
1456 edges_count=1; /* zero element is a sentinel and a head */
1457 ALLOCATE(edges,edges_num);
1458 @
1459
1460 @<functions@>=
1461 uint16_t new_edge(void)
1462 { if (edges_count<edges_num)
1463 return edges_count++;
1464 REALLOC(edges,edges_count,edges_num);
1465 return edges_count++;
1466 }
1467 @
1468
1469 When a parent macro with definition |p| calls
1470 a child macro with definition |c|, the |start_child| function
1471 is called after the new child macro is put on top of the macro stack.
1472 We first search the existing edges of the parent for an existing
1473 edge, possibly from a previous invocation, before we add a new edge.
1474 Once the edge is found, we increment |count| and |a|.
1475 If |a| changes from zero to one we update |T|, |L|, |ts|, and |Ts|
1476 as described above.
1477
1478 @<functions@>=
1479 void start_child(int p, int c)
1480 { int e =macro_defs[p].e;
1481 if (e==0)
1482 { e =new_edge();
1483 macro_defs[p].e=e;
1484 edges[e].child=c;
1485 goto found;
1486 }
1487 do
1488 { if (edges[e].child==c)
1489 goto found;
1490 else if (edges[e].sibling==0)
1491 { int s=new_edge();
1492 edges[e].sibling=s;
1493 e = s;
1494 edges[e].child=c;
1495 goto found;
1496 }
1497 else
1498 e = edges[e].sibling;
1499 } while (true);
1500 found:
1501 edges[e].a++;
1502 edges[e].count++;
1503 if (edges[e].a==1)
1504 { uint16_t i;
1505 edges[e].ts=total_time;
1506 edges[e].Ts=macro_defs[p].t;
1507 for (i= macro_defs[p].e;i!=0;i=edges[i].sibling)
1508 if (i!=e)
1509 edges[e].Ts +=edges[i].T;
1510 }
1511 }
1512 @
1513
1514
1515 When we pop a child macro, we use the following function
1516 to update |a| and in the case of |a==1| also |T| and |L|.
1517
1518 @<functions@>=
1519 void end_child(int p, int c)
1520 { uint16_t e = macro_defs[p].e;
1521 while (e!=0)
1522 { if (edges[e].child==c)
1523 goto found;
1524 else
1525 e = edges[e].sibling;
1526 }
1527 found:
1528 if (edges[e].a==1)
1529 { uint16_t i;
1530 uint64_t dt;
1531 uint64_t dT;
1532 dT=macro_defs[p].t;
1533 for (i= macro_defs[p].e;i!=0;i=edges[i].sibling)
1534 if (i!=e)
1535 dT +=edges[i].T;
1536 dt=total_time-edges[e].ts;
1537 dT=dT-edges[e].Ts;
1538 edges[e].L+=dT;
1539 edges[e].T+=dt-dT;
1540 }
1541 edges[e].a--;
1542 }
1543 @
1544
1545 The information contained in the edges gives
1546 a good view of the call graph. It can be shown using the ``{\tt -G}'' option.
1547
1548 @ @<declarations@>=
1549 bool opt_graph=false;
1550 @
1551
1552 @<process options@>=
1553 case 'G': opt_graph=true; break;
1554 @
1555
1556 @<explain table options@>=
1557 "-G show the table of the macro call graph\n"@;
1558 @
1559
1560 @<show the macro call graph if requested@>=
1561 if (opt_graph)
1562 { sort_macros();
1563 Mprintf("\nThe macro call graph:\n"
1564 " time\t loop\tpercent\t count/total\tchild\n");
1565 i=macro_defs[0].link;
1566 do
1567 { int e;
1568 uint64_t Ti=macro_defs[i].T;
1569 if (100.0*Ti/total_time<percent_limit)
1570 break;
1571 print_macro(i);
1572 printf("\n");
1573 printf("%s\t \t%6.2f%%\t",
1574 time_str(Ti), 100.0*Ti/total_time);
1575 if (opt_machine)
1576 printf("\t%6d\t",macro_defs[i].count);
1577 else
1578 printf(" * \t");
1579 print_macro(i);
1580 printf("\n");
1581 printf("%s\t \t", time_str(macro_defs[i].t));
1582 if (Ti!=0)
1583 printf("%6.2f%%\t", 100.0*macro_defs[i].t/Ti);
1584 else
1585 printf("\t");
1586 if (opt_machine)
1587 printf("%6d\t\t",macro_defs[i].count);
1588 else
1589 printf("%7d \t",macro_defs[i].count);
1590 print_macro(i);
1591 printf("\n");
1592 e =macro_defs[i].e;
1593 while (e!=0)
1594 { int c = edges[e].child;
1595 int n =edges[e].count;
1596 int m =macro_defs[c].count;
1597 uint64_t Te=edges[e].T;
1598 int64_t L=edges[e].L;
1599 double p= 100.0*Te/Ti;
1600 if (p>=percent_limit)
1601 { printf("%s\t",time_str(Te));
1602 if (L==0 && !opt_machine)
1603 printf(" \t");
1604 else
1605 printf("%s\t", time_str(L));
1606 if (Ti!=0)
1607 printf("%6.2f%%\t", p);
1608 else
1609 printf("\t");
1610 if (opt_machine)
1611 printf("%6d\t%6d\t",n,m);
1612 else
1613 printf("%6d/%-6d\t",n,m);
1614 print_macro(c);
1615 printf("\n");
1616 }
1617 e = edges[e].sibling;
1618 }
1619 printf("\n");
1620 i=macro_defs[i].link;
1621 } while (i!=0);
1622 }
1623 @
1624
1625
1626 \subsection{All Tables}
1627
1628 Now its time to bring all the different output tables together
1629 in a useful sequence.
1630
1631 @<process options@>=
1632 case 'A': opt_files=opt_summary=
1633 opt_cmd=opt_top_ten=
1634 opt_graph=true; break;
1635 @
1636
1637 @<explain table options@>=
1638 "-A show all tables (equal to -TGFC) tables\n"@;
1639 @
1640
1641 @<write the output file@>=
1642 @<show all time stamps if requested@>@;
1643 @<show the complete macro stack if requested@>@;
1644 @<show the command summary if requested@>@;
1645 @<show the file summary if requested@>@;
1646 @<show lines above limit if requested@>@;
1647 @<show the top ten lines@>@;
1648 @<show the table of macros profiled if requested@>@;
1649 @<show the macro call graph if requested@>@;
1650 @<show the total time if requested@>@;
1651 @
1652
1653
1654 \section{Processing the Command Line}
1655
1656
1657 @<process the command line@>=
1658 i=1;
1659 while (i<argc)
1660 { char *option;
1661 if (argv[i][0]=='-')
1662 { option=argv[i]+1;
1663 while (*option!=0)
1664 { switch(*option)
1665 { @<process options@>@;
1666 default: commandline_error("unknown option");
1667 }
1668 option++;
1669 }
1670 }
1671 else if (input_file_name==NULL)
1672 input_file_name=argv[i];
1673 else
1674 commandline_error("multiple input files given");
1675 i++;
1676 }
1677 @
1678
1679
1680 Sometimes an error means that the program should also explain how to use it.
1681
1682 @<functions@>=
1683 void explain_usage(void)
1684 { fprintf(stderr,
1685 "Use: "@;
1686 "texprofile [-options] <input file>\n"@;
1687 "options:\n"@;
1688 @<explain general options@>@;
1689 "\n"
1690 @<explain table options@>@;
1691 "\n"
1692 @<explain format options@>@;
1693 "\n"
1694 );
1695 exit(0);
1696 }
1697 @
1698
1699 A simple option that most users will use occasionaly is the {\tt -?} option.
1700 This option can also be look like {\tt --help}, {\tt -help} or {\tt -h}.
1701
1702 @<process options@>=
1703 case 'h':
1704 case '?': explain_usage(); break;
1705 @
1706
1707 @<explain general options@>=
1708 "-? display this help and exit\n"@;
1709 "--help display this help and exit\n"@;
1710 @
1711
1712 The help option should also be available as a long option:
1713
1714 @<process options@>=
1715 case '-':
1716 option++;
1717 @<process long options@>@;
1718 else commandline_error("unknown long option");
1719 break;
1720 @
1721
1722 @<process long options@>=
1723 if (strcmp(option,"help")==0) explain_usage();
1724 @
1725
1726 The only other long option currently supported is the {\tt --version} option.
1727
1728 @d VERSION_STR "1.1"
1729
1730 @<process long options@>=
1731 if (strcmp(option,"version")==0)
1732 { printf("texprofile version " VERSION_STR "\n");
1733 exit(0);
1734 }
1735 @
1736
1737 @<explain general options@>=
1738 "--version output version information and exit\n"@;
1739 @
1740
1741 \section{Error Handling}
1742 If an error occurs this program will print an error message
1743 and terminate. There is no attempt to recover from errors.
1744
1745 @<error handling@>=
1746 int error(char *msg)
1747 { fprintf(stderr,"texprofile: %s\n", msg);
1748 exit(1);
1749 return 0;
1750 }
1751 @
1752
1753 The program is a little bit more verbose if there is an error in the
1754 command line.
1755
1756 @<error handling@>=
1757 int commandline_error(char *msg)
1758 { fprintf(stderr,"texprofile: %s\n", msg);
1759 fprintf(stderr,"Try 'texprofile --help' for more information.\n");
1760 exit(1);
1761 return 0;
1762 }
1763 @
1764
1765
1766
1767
1768 The input file should start with a marker: the ASCII codes of ``TEX PROF''.
1769 The same marker is used later to separate the different sections of the file.
1770
1771 @<functions@>=
1772 void check_file_marker(char *msg)
1773 { char marker[8];
1774 if (fread(marker,1,8,in)!=8)
1775 error("Unexpected end of input");
1776 if(strncmp(marker,FILE_MARKER,8)!=0)
1777 error(msg);
1778 }
1779 @
1780
1781 \appendix
1782
1783 \section{The Table of Command Names}
1784 To print commands nicely, here is an array of command names. Some
1785 of the commands also have names to be able to test for them;
1786 the definitions are taken from {\tt texprof.w}.
1787
1788 @d max_command 100 /*the largest command code seen at |big_switch|*/
1789
1790 @d system_cmd (max_command+1) /*pseudo command value*/
1791 @d system_profile_on (system_cmd+1)
1792 @d system_profile_off (system_cmd+2)
1793 @d system_macro_push (system_cmd+3)
1794 @d system_macro_pop (system_cmd+4)
1795 @d system_macro_pop_small (system_cmd+5)
1796 @d system_macro_pop_0 (system_cmd+6)
1797
1798 @<declarations@>=
1799 static char *cmd_name[]= {@/
1800 "relax", /*do nothing ( \.{\\relax} )*/
1801 "left_brace", /*beginning of a group ( \.\{ )*/
1802 "right_brace", /*ending of a group ( \.\} )*/
1803 "math_shift", /*mathematics shift character ( \.\$ )*/
1804 "tab_mark", /*alignment delimiter ( \.\&, \.{\\span} )*/
1805 "car_ret/" /*end of line ( |carriage_return|, \.{\\cr}, \.{\\crcr} )*/
1806 "out_param", /*output a macro parameter*/
1807 "mac_param", /*macro parameter symbol ( \.\# )*/
1808 "sup_mark", /*superscript ( \.{\char'136} )*/
1809 "sub_mark", /*subscript ( \.{\char'137} )*/
1810 "ignore/" /*characters to ignore ( \.{\^\^@@} )*/
1811 "endv", /*end of \<$v_j$> list in alignment template*/
1812 "spacer", /*characters equivalent to blank space ( \.{\ } )*/
1813 "letter", /*characters regarded as letters ( \.{A..Z}, \.{a..z} )*/
1814 "other_char", /*none of the special character types*/
1815 "active/" /*characters that invoke macros ( \.{\char`\~} )*/
1816 "par/" /*end of paragraph ( \.{\\par} )*/
1817 "match", /*match a macro parameter*/
1818 "comment/" /*characters that introduce comments ( \.\% )*/
1819 "end_match/" /*end of parameters to macro*/
1820 "stop", /*end of job ( \.{\\end}, \.{\\dump} )*/
1821 "invalid_char/" /*characters that shouldn't appear ( \.{\^\^?} )*/
1822 "delim_num", /*specify delimiter numerically ( \.{\\delimiter} )*/
1823
1824 "char_num", /*character specified numerically ( \.{\\char} )*/
1825 "math_char_num", /*explicit math code ( \.{\\mathchar} )*/
1826 "mark", /*mark definition ( \.{\\mark} )*/
1827 "xray", /*peek inside of \TeX\ ( \.{\\show}, \.{\\showbox}, etc.~)*/
1828 "make_box", /*make a box ( \.{\\box}, \.{\\copy}, \.{\\hbox}, etc.~)*/
1829 "hmove", /*horizontal motion ( \.{\\moveleft}, \.{\\moveright} )*/
1830 "vmove", /*vertical motion ( \.{\\raise}, \.{\\lower} )*/
1831 "un_hbox", /*unglue a box ( \.{\\unhbox}, \.{\\unhcopy} )*/
1832 "un_vbox", /*unglue a box ( \.{\\unvbox}, \.{\\unvcopy} \dots )*/
1833
1834 "remove_item", /*nullify last item ( \.{\\unpenalty}, \dots )*/
1835 "hskip", /*horizontal glue ( \.{\\hskip}, \.{\\hfil}, etc.~)*/
1836 "vskip", /*vertical glue ( \.{\\vskip}, \.{\\vfil}, etc.~)*/
1837 "mskip", /*math glue ( \.{\\mskip} )*/
1838 "kern", /*fixed space ( \.{\\kern} )*/
1839 "mkern", /*math kern ( \.{\\mkern} )*/
1840 "leaders/shipout", /*use a box ( \.{\\shipout}, \.{\\leaders}, etc.~)*/
1841 "halign", /*horizontal table alignment ( \.{\\halign} )*/
1842 "valign", /*vertical table alignment ( \.{\\valign} )*/
1843 "no_align", /*temporary escape from alignment ( \.{\\noalign} )*/
1844 "vrule", /*vertical rule ( \.{\\vrule} )*/
1845 "hrule", /*horizontal rule ( \.{\\hrule} )*/
1846 "insert", /*vlist inserted in box ( \.{\\insert} )*/
1847 "vadjust", /*vlist inserted in enclosing paragraph ( \.{\\vadjust} )*/
1848 "ignore_spaces", /*gobble |spacer| tokens ( \.{\\ignorespaces} )*/
1849 "after_assignment", /*save till assignment is done ( \.{\\afterassignment} )*/
1850 "after_group", /*save till group is done ( \.{\\aftergroup} )*/
1851 "break_penalty", /*additional badness ( \.{\\penalty} )*/
1852 "start_par", /*begin paragraph ( \.{\\indent}, \.{\\noindent} )*/
1853 "ital_corr", /*italic correction ( \.{\\/} )*/
1854 "accent", /*attach accent in text ( \.{\\accent} )*/
1855 "math_accent", /*attach accent in math ( \.{\\mathaccent} )*/
1856 "discretionary", /*discretionary texts ( \.{\\-}, \.{\\discretionary} )*/
1857 "eq_no", /*equation number ( \.{\\eqno}, \.{\\leqno} )*/
1858 "left_right", /*variable delimiter ( \.{\\left}, \.{\\right} ) \dots )*/
1859 "math_comp", /*component of formula ( \.{\\mathbin}, etc.~)*/
1860 "limit_switch", /*diddle limit conventions ( \.{\\displaylimits}, etc.~)*/
1861 "above", /*generalized fraction ( \.{\\above}, \.{\\atop}, etc.~)*/
1862 "math_style", /*style specification ( \.{\\displaystyle}, etc.~)*/
1863 "math_choice", /*choice specification ( \.{\\mathchoice} )*/
1864 "non_script", /*conditional math glue ( \.{\\nonscript} )*/
1865 "vcenter", /*vertically center a vbox ( \.{\\vcenter} )*/
1866 "case_shift", /*force specific case ( \.{\\lowercase}, \.{\\uppercase}~)*/
1867 "message", /*send to user ( \.{\\message}, \.{\\errmessage} )*/
1868 "extension", /*extensions to \TeX\ ( \.{\\write}, \.{\\special}, etc.~)*/
1869 "in_stream", /*files for reading ( \.{\\openin}, \.{\\closein} )*/
1870 "begin_group", /*begin local grouping ( \.{\\begingroup} )*/
1871 "end_group", /*end local grouping ( \.{\\endgroup} )*/
1872 "omit", /*omit alignment template ( \.{\\omit} )*/
1873 "ex_space", /*explicit space ( \.{\\\ } )*/
1874 "no_boundary", /*suppress boundary ligatures ( \.{\\noboundary} )*/
1875 "radical", /*square root and similar signs ( \.{\\radical} )*/
1876 "end_cs_name", /*end control sequence ( \.{\\endcsname} )*/
1877 "min_internal/" /*the smallest code that can follow \.{\\the}*/
1878 "char_given", /*character code defined by \.{\\chardef}*/
1879 "math_given", /*math code defined by \.{\\mathchardef}*/
1880 "last_item", /*most recent item ( \.{\\lastpenalty},\dots )*/
1881
1882 "toks_register", /*token list register ( \.{\\toks} )*/
1883 "assign_toks", /*special token list ( \.{\\output}, \.{\\everypar}, etc.~)*/
1884 "assign_int", /*user-defined integer ( \.{\\tolerance}, \.{\\day}, etc.~)*/
1885 "assign_dimen", /*user-defined length ( \.{\\hsize}, etc.~)*/
1886 "assign_glue", /*user-defined glue ( \.{\\baselineskip}, etc.~)*/
1887 "assign_mu_glue", /*user-defined muglue ( \.{\\thinmuskip}, etc.~)*/
1888 "assign_font_dimen", /*user-defined font dimension ( \.{\\fontdimen} )*/
1889 "assign_font_int", /*user-defined font integer ( \.{\\hyphenchar}, \dots )*/
1890 "set_aux", /*specify state info ( \.{\\spacefactor}, \.{\\prevdepth} )*/
1891 "set_prev_graf", /*specify state info ( \.{\\prevgraf} )*/
1892 "set_page_dimen", /*specify state info ( \.{\\pagegoal}, etc.~)*/
1893 "set_page_int", /*specify state info ( \.{\\deadcycles}, \dots )*/
1894 "set_box_dimen", /*change dimension of box ( \.{\\wd}, \.{\\ht}, \.{\\dp} )*/
1895 "set_shape", /*specify fancy paragraph shape ( \.{\\parshape} ) \dots )*/
1896 "def_code", /*define a character code ( \.{\\catcode}, etc.~)*/
1897 "def_family", /*declare math fonts ( \.{\\textfont}, etc.~)*/
1898 "set_font", /*set current font ( font identifiers )*/
1899 "def_font", /*define a font file ( \.{\\font} )*/
1900 "internal_register", /*internal register ( \.{\\count}, \.{\\dimen}, etc.~)*/
1901 "advance", /*advance a register or parameter ( \.{\\advance} )*/
1902 "multiply", /*multiply a register or parameter ( \.{\\multiply} )*/
1903 "divide", /*divide a register or parameter ( \.{\\divide} )*/
1904 "prefix", /*qualify a definition ( \.{\\global}, \.{\\long}, \.{\\outer} etc.~) )*/
1905 "let", /*assign a command code ( \.{\\let}, \.{\\futurelet} )*/
1906 "shorthand_def", /*code definition ( \.{\\chardef}, \.{\\countdef}, etc.~)*/
1907 "read_to_cs", /*read into a control sequence ( \.{\\read}, etc.~)*/
1908 "def", /*macro definition ( \.{\\def}, \.{\\gdef}, \.{\\xdef}, \.{\\edef} )*/
1909 "set_box", /*set a box ( \.{\\setbox} )*/
1910 "hyph_data", /*hyphenation data ( \.{\\hyphenation}, \.{\\patterns} )*/
1911 "set_interaction", /*define level of interaction ( \.{\\batchmode}, etc.~)*/
1912
1913 "system", /*system start*/
1914 "profile on", /*switching on profile ( \.{\\profileon} )*/
1915 "profile off", /*switching on profile ( \.{\\profileoff} )*/
1916 "call", /*macro call*/
1917 "pop", /*macro return*/
1918 "pop n", /*macro return*/
1919 "pop 0", /*macro return*/
1920 "pop 1", /*macro return*/
1921 "pop 2", /*macro return*/
1922 "pop 3", /*macro return*/
1923 "pop 4", /*macro return*/
1924 "pop 5", /*macro return*/
1925 "pop 6", /*macro return*/
1926 "pop 7", /*macro return*/
1927 "pop 8", /*macro return*/
1928 "pop 9", /*macro return*/
1929 "pop 10", /*macro return*/
1930 "unknown" /*should not happen*/
1931 };
1932
1933 static const int cmd_num=sizeof(cmd_name)/sizeof(*cmd_name);
1934
1935 #define CMD_NAME(N) ((N)<cmd_num?cmd_name[N]:"unknown")
1936
1937 static char *line_name[]= {@/ /*for the system pseudo file*/
1938 "unknown", /*as it says*/
1939 "start", /*time before executing the first command*/
1940 "end", /*time after executing the last command*/
1941 "shipout", /*time spent writing the dvi file*/
1942 "linebrk", /*time spent on line breaking*/
1943 "initrie", /*time spent on setting up hyphenation*/
1944 "buildpg", /*time spent in |build_page|*/
1945 "inputln", /*time spent in |input_ln|*/
1946 "insert", /*time spent on tokens inserted by \TeX*/
1947 };
1948
1949 static char *every_name[]={@/ /* names for output, everypar, etc. */
1950 "output", /*for output routines*/
1951 "everypar", /*for \.{\\everypar}*/
1952 "everymath", /*for \.{\\everymath}*/
1953 "everydisplay", /*for \.{\\everydisplay}*/
1954 "everyhbox", /*for \.{\\everyhbox}*/
1955 "everyvbox", /*for \.{\\everyvbox}*/
1956 "everyjob", /*for \.{\\everyjob}*/
1957 "everycr", /*for \.{\\everycr}*/
1958 "mark", /*for \.{\\topmark}, etc.*/
1959 "everyeof" /*for \.{\\everyeof}*/
1960 };
1961
1962 static const int sys_line_num=sizeof(line_name)/sizeof(*line_name);
1963 @
1964
1965 %\plainsection{References}
1966
1967 %{\baselineskip=11pt
1968 %\def\bfblrm{\small\rm}%
1969 %\def\bblem{\small\it}%
1970 %\bibliography{../hint}
1971 %\bibliographystyle{plain}
1972 %}
1973
1974 %\plainsection{Index}
1975 %{
1976 %\def\_{{\tt \UL}} % underline in a string
1977 %\catcode`\_=\active \let_=\_ % underline is a letter
1978 %\input texprofile.ind
1979 %}
1980
1981 \write\cont{} % ensure that the contents file isn't empty
1982 % \write\cont{\catcode `\noexpand\@=12\relax} % \makeatother
1983 \closeout\cont% the contents information has been fully gathered