Merge from emacs-24 branch; up to 2012-05-01T10:20:43Z!rgm@gnu.org
[bpt/emacs.git] / lib-src / profile.c
1 /* profile.c --- generate periodic events for profiling of Emacs Lisp code.
2 Copyright (C) 1992, 1994, 1999, 2001-2012 Free Software Foundation, Inc.
3
4 Author: Boaz Ben-Zvi <boaz@lcs.mit.edu>
5
6 This file is part of GNU Emacs.
7
8 GNU Emacs is free software: you can redistribute it and/or modify
9 it under the terms of the GNU General Public License as published by
10 the Free Software Foundation, either version 3 of the License, or
11 (at your option) any later version.
12
13 GNU Emacs is distributed in the hope that it will be useful,
14 but WITHOUT ANY WARRANTY; without even the implied warranty of
15 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 GNU General Public License for more details.
17
18 You should have received a copy of the GNU General Public License
19 along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>. */
20
21
22 /**
23 ** To be run as an emacs subprocess. Input string that starts with:
24 ** 'z' -- resets the watch (to zero).
25 ** 'p' -- return time (on stdout) as string with format <sec>.<micro-sec>
26 ** 'q' -- exit.
27 **
28 ** abstraction : a stopwatch
29 ** operations: reset_watch, get_time
30 */
31 #include <config.h>
32
33 #include <inttypes.h>
34 #include <stdio.h>
35
36 #include <intprops.h>
37 #include <systime.h>
38
39 static EMACS_TIME TV1;
40 static int watch_not_started = 1; /* flag */
41 static char time_string[INT_STRLEN_BOUND (uintmax_t) + sizeof "."
42 + LOG10_EMACS_TIME_RESOLUTION];
43
44 /* Reset the stopwatch to zero. */
45
46 static void
47 reset_watch (void)
48 {
49 TV1 = current_emacs_time ();
50 watch_not_started = 0;
51 }
52
53 /* This call returns the time since the last reset_watch call. The time
54 is returned as a string with the format <seconds>.<nanoseconds>
55 If reset_watch was not called yet, exit. */
56
57 static char *
58 get_time (void)
59 {
60 EMACS_TIME TV2 = sub_emacs_time (current_emacs_time (), TV1);
61 uintmax_t s = EMACS_SECS (TV2);
62 int ns = EMACS_NSECS (TV2);
63 if (watch_not_started)
64 exit (EXIT_FAILURE); /* call reset_watch first ! */
65 sprintf (time_string, "%"PRIuMAX".%0*d", s, LOG10_EMACS_TIME_RESOLUTION, ns);
66 return time_string;
67 }
68 \f
69 int
70 main (void)
71 {
72 int c;
73 while ((c = getchar ()) != EOF)
74 {
75 switch (c)
76 {
77 case 'z':
78 reset_watch ();
79 break;
80 case 'p':
81 puts (get_time ());
82 break;
83 case 'q':
84 exit (EXIT_SUCCESS);
85 }
86 /* Anything remaining on the line is ignored. */
87 while (c != '\n' && c != EOF)
88 c = getchar ();
89 }
90 exit (EXIT_FAILURE);
91 }
92
93
94 /* profile.c ends here */