Fixed bug in time-to-midnight calculation.
[python.git] / Modules / _hotshot.c
blob758c4ee04c92f17027d0e03e5588a8b28b901ff5
1 /*
2 * This is the High Performance Python Profiler portion of HotShot.
3 */
5 #include "Python.h"
6 #include "code.h"
7 #include "eval.h"
8 #include "frameobject.h"
9 #include "structmember.h"
12 * Which timer to use should be made more configurable, but that should not
13 * be difficult. This will do for now.
15 #ifdef MS_WINDOWS
16 #include <windows.h>
17 #include <direct.h> /* for getcwd() */
18 typedef __int64 hs_time;
19 #define GETTIMEOFDAY(P_HS_TIME) \
20 { LARGE_INTEGER _temp; \
21 QueryPerformanceCounter(&_temp); \
22 *(P_HS_TIME) = _temp.QuadPart; }
25 #else
26 #ifndef HAVE_GETTIMEOFDAY
27 #error "This module requires gettimeofday() on non-Windows platforms!"
28 #endif
29 #if (defined(PYOS_OS2) && defined(PYCC_GCC))
30 #include <sys/time.h>
31 #else
32 #include <sys/resource.h>
33 #include <sys/times.h>
34 #endif
35 typedef struct timeval hs_time;
36 #endif
38 #if !defined(__cplusplus) && !defined(inline)
39 #ifdef __GNUC__
40 #define inline __inline
41 #endif
42 #endif
44 #ifndef inline
45 #define inline
46 #endif
48 #define BUFFERSIZE 10240
50 #if defined(PYOS_OS2) && defined(PYCC_GCC)
51 #define PATH_MAX 260
52 #endif
54 #if defined(__sgi) && _COMPILER_VERSION>700 && !defined(PATH_MAX)
55 /* fix PATH_MAX not being defined with MIPSPro 7.x
56 if mode is ANSI C (default) */
57 #define PATH_MAX 1024
58 #endif
60 #ifndef PATH_MAX
61 # ifdef MAX_PATH
62 # define PATH_MAX MAX_PATH
63 # elif defined (_POSIX_PATH_MAX)
64 # define PATH_MAX _POSIX_PATH_MAX
65 # else
66 # error "Need a defn. for PATH_MAX in _hotshot.c"
67 # endif
68 #endif
70 typedef struct {
71 PyObject_HEAD
72 PyObject *filemap;
73 PyObject *logfilename;
74 int index;
75 unsigned char buffer[BUFFERSIZE];
76 FILE *logfp;
77 int lineevents;
78 int linetimings;
79 int frametimings;
80 /* size_t filled; */
81 int active;
82 int next_fileno;
83 hs_time prev_timeofday;
84 } ProfilerObject;
86 typedef struct {
87 PyObject_HEAD
88 PyObject *info;
89 FILE *logfp;
90 int linetimings;
91 int frametimings;
92 } LogReaderObject;
94 static PyObject * ProfilerError = NULL;
97 #ifndef MS_WINDOWS
98 #ifdef GETTIMEOFDAY_NO_TZ
99 #define GETTIMEOFDAY(ptv) gettimeofday((ptv))
100 #else
101 #define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
102 #endif
103 #endif
106 /* The log reader... */
108 PyDoc_STRVAR(logreader_close__doc__,
109 "close()\n"
110 "Close the log file, preventing additional records from being read.");
112 static PyObject *
113 logreader_close(LogReaderObject *self, PyObject *args)
115 if (self->logfp != NULL) {
116 fclose(self->logfp);
117 self->logfp = NULL;
119 Py_INCREF(Py_None);
121 return Py_None;
124 PyDoc_STRVAR(logreader_fileno__doc__,
125 "fileno() -> file descriptor\n"
126 "Returns the file descriptor for the log file, if open.\n"
127 "Raises ValueError if the log file is closed.");
129 static PyObject *
130 logreader_fileno(LogReaderObject *self)
132 if (self->logfp == NULL) {
133 PyErr_SetString(PyExc_ValueError,
134 "logreader's file object already closed");
135 return NULL;
137 return PyInt_FromLong(fileno(self->logfp));
141 /* Log File Format
142 * ---------------
144 * The log file consists of a sequence of variable-length records.
145 * Each record is identified with a record type identifier in two
146 * bits of the first byte. The two bits are the "least significant"
147 * bits of the byte.
149 * Low bits: Opcode: Meaning:
150 * 0x00 ENTER enter a frame
151 * 0x01 EXIT exit a frame
152 * 0x02 LINENO execution moved onto a different line
153 * 0x03 OTHER more bits are needed to deecode
155 * If the type is OTHER, the record is not packed so tightly, and the
156 * remaining bits are used to disambiguate the record type. These
157 * records are not used as frequently so compaction is not an issue.
158 * Each of the first three record types has a highly tailored
159 * structure that allows it to be packed tightly.
161 * The OTHER records have the following identifiers:
163 * First byte: Opcode: Meaning:
164 * 0x13 ADD_INFO define a key/value pair
165 * 0x23 DEFINE_FILE define an int->filename mapping
166 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
167 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
168 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
170 * Packed Integers
172 * "Packed integers" are non-negative integer values encoded as a
173 * sequence of bytes. Each byte is encoded such that the most
174 * significant bit is set if the next byte is also part of the
175 * integer. Each byte provides bits to the least-significant end of
176 * the result; the accumulated value must be shifted up to place the
177 * new bits into the result.
179 * "Modified packed integers" are packed integers where only a portion
180 * of the first byte is used. In the rest of the specification, these
181 * are referred to as "MPI(n,name)", where "n" is the number of bits
182 * discarded from the least-signicant positions of the byte, and
183 * "name" is a name being given to those "discarded" bits, since they
184 * are a field themselves.
186 * ENTER records:
188 * MPI(2,type) fileno -- type is 0x00
189 * PI lineno
190 * PI tdelta -- iff frame times are enabled
192 * EXIT records
194 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
195 * if frame times are disabled
197 * LINENO records
199 * MPI(2,type) lineno -- type is 0x02
200 * PI tdelta -- iff LINENO includes it
202 * ADD_INFO records
204 * BYTE type -- always 0x13
205 * PI len1 -- length of first string
206 * BYTE string1[len1] -- len1 bytes of string data
207 * PI len2 -- length of second string
208 * BYTE string2[len2] -- len2 bytes of string data
210 * DEFINE_FILE records
212 * BYTE type -- always 0x23
213 * PI fileno
214 * PI len -- length of filename
215 * BYTE filename[len] -- len bytes of string data
217 * DEFINE_FUNC records
219 * BYTE type -- always 0x43
220 * PI fileno
221 * PI lineno
222 * PI len -- length of funcname
223 * BYTE funcname[len] -- len bytes of string data
225 * LINE_TIMES records
227 * This record can be used only before the start of ENTER/EXIT/LINENO
228 * records. If have_tdelta is true, LINENO records will include the
229 * tdelta field, otherwise it will be omitted. If this record is not
230 * given, LINENO records will not contain the tdelta field.
232 * BYTE type -- always 0x33
233 * BYTE have_tdelta -- 0 if LINENO does *not* have
234 * timing information
235 * FRAME_TIMES records
237 * This record can be used only before the start of ENTER/EXIT/LINENO
238 * records. If have_tdelta is true, ENTER and EXIT records will
239 * include the tdelta field, otherwise it will be omitted. If this
240 * record is not given, ENTER and EXIT records will contain the tdelta
241 * field.
243 * BYTE type -- always 0x53
244 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
245 * timing information
248 #define WHAT_ENTER 0x00
249 #define WHAT_EXIT 0x01
250 #define WHAT_LINENO 0x02
251 #define WHAT_OTHER 0x03 /* only used in decoding */
252 #define WHAT_ADD_INFO 0x13
253 #define WHAT_DEFINE_FILE 0x23
254 #define WHAT_LINE_TIMES 0x33
255 #define WHAT_DEFINE_FUNC 0x43
256 #define WHAT_FRAME_TIMES 0x53
258 #define ERR_NONE 0
259 #define ERR_EOF -1
260 #define ERR_EXCEPTION -2
261 #define ERR_BAD_RECTYPE -3
263 #define PISIZE (sizeof(int) + 1)
264 #define MPISIZE (PISIZE + 1)
266 /* Maximum size of "normal" events -- nothing that contains string data */
267 #define MAXEVENTSIZE (MPISIZE + PISIZE*2)
270 /* Unpack a packed integer; if "discard" is non-zero, unpack a modified
271 * packed integer with "discard" discarded bits.
273 static int
274 unpack_packed_int(LogReaderObject *self, int *pvalue, int discard)
276 int c;
277 int accum = 0;
278 int bits = 0;
279 int cont;
281 do {
282 /* read byte */
283 if ((c = fgetc(self->logfp)) == EOF)
284 return ERR_EOF;
285 accum |= ((c & 0x7F) >> discard) << bits;
286 bits += (7 - discard);
287 cont = c & 0x80;
288 discard = 0;
289 } while (cont);
291 *pvalue = accum;
293 return 0;
296 /* Unpack a string, which is encoded as a packed integer giving the
297 * length of the string, followed by the string data.
299 static int
300 unpack_string(LogReaderObject *self, PyObject **pvalue)
302 int i;
303 int len;
304 int err;
305 int ch;
306 char *buf;
308 if ((err = unpack_packed_int(self, &len, 0)))
309 return err;
311 buf = malloc(len);
312 for (i=0; i < len; i++) {
313 ch = fgetc(self->logfp);
314 buf[i] = ch;
315 if (ch == EOF) {
316 free(buf);
317 return ERR_EOF;
320 *pvalue = PyString_FromStringAndSize(buf, len);
321 free(buf);
322 if (*pvalue == NULL) {
323 return ERR_EXCEPTION;
325 return 0;
329 static int
330 unpack_add_info(LogReaderObject *self)
332 PyObject *key;
333 PyObject *value = NULL;
334 int err;
336 err = unpack_string(self, &key);
337 if (!err) {
338 err = unpack_string(self, &value);
339 if (err)
340 Py_DECREF(key);
341 else {
342 PyObject *list = PyDict_GetItem(self->info, key);
343 if (list == NULL) {
344 list = PyList_New(0);
345 if (list == NULL) {
346 err = ERR_EXCEPTION;
347 goto finally;
349 if (PyDict_SetItem(self->info, key, list)) {
350 Py_DECREF(list);
351 err = ERR_EXCEPTION;
352 goto finally;
354 Py_DECREF(list);
356 if (PyList_Append(list, value))
357 err = ERR_EXCEPTION;
360 finally:
361 Py_XDECREF(key);
362 Py_XDECREF(value);
363 return err;
367 static void
368 eof_error(LogReaderObject *self)
370 fclose(self->logfp);
371 self->logfp = NULL;
372 PyErr_SetString(PyExc_EOFError,
373 "end of file with incomplete profile record");
376 static PyObject *
377 logreader_tp_iternext(LogReaderObject *self)
379 int c;
380 int what;
381 int err = ERR_NONE;
382 int lineno = -1;
383 int fileno = -1;
384 int tdelta = -1;
385 PyObject *s1 = NULL, *s2 = NULL;
386 PyObject *result = NULL;
387 #if 0
388 unsigned char b0, b1;
389 #endif
391 if (self->logfp == NULL) {
392 PyErr_SetString(ProfilerError,
393 "cannot iterate over closed LogReader object");
394 return NULL;
397 restart:
398 /* decode the record type */
399 if ((c = fgetc(self->logfp)) == EOF) {
400 fclose(self->logfp);
401 self->logfp = NULL;
402 return NULL;
404 what = c & WHAT_OTHER;
405 if (what == WHAT_OTHER)
406 what = c; /* need all the bits for type */
407 else
408 ungetc(c, self->logfp); /* type byte includes packed int */
410 switch (what) {
411 case WHAT_ENTER:
412 err = unpack_packed_int(self, &fileno, 2);
413 if (!err) {
414 err = unpack_packed_int(self, &lineno, 0);
415 if (self->frametimings && !err)
416 err = unpack_packed_int(self, &tdelta, 0);
418 break;
419 case WHAT_EXIT:
420 err = unpack_packed_int(self, &tdelta, 2);
421 break;
422 case WHAT_LINENO:
423 err = unpack_packed_int(self, &lineno, 2);
424 if (self->linetimings && !err)
425 err = unpack_packed_int(self, &tdelta, 0);
426 break;
427 case WHAT_ADD_INFO:
428 err = unpack_add_info(self);
429 break;
430 case WHAT_DEFINE_FILE:
431 err = unpack_packed_int(self, &fileno, 0);
432 if (!err) {
433 err = unpack_string(self, &s1);
434 if (!err) {
435 Py_INCREF(Py_None);
436 s2 = Py_None;
439 break;
440 case WHAT_DEFINE_FUNC:
441 err = unpack_packed_int(self, &fileno, 0);
442 if (!err) {
443 err = unpack_packed_int(self, &lineno, 0);
444 if (!err)
445 err = unpack_string(self, &s1);
447 break;
448 case WHAT_LINE_TIMES:
449 if ((c = fgetc(self->logfp)) == EOF)
450 err = ERR_EOF;
451 else {
452 self->linetimings = c ? 1 : 0;
453 goto restart;
455 break;
456 case WHAT_FRAME_TIMES:
457 if ((c = fgetc(self->logfp)) == EOF)
458 err = ERR_EOF;
459 else {
460 self->frametimings = c ? 1 : 0;
461 goto restart;
463 break;
464 default:
465 err = ERR_BAD_RECTYPE;
467 if (err == ERR_BAD_RECTYPE) {
468 PyErr_SetString(PyExc_ValueError,
469 "unknown record type in log file");
471 else if (err == ERR_EOF) {
472 eof_error(self);
474 else if (!err) {
475 result = PyTuple_New(4);
476 PyTuple_SET_ITEM(result, 0, PyInt_FromLong(what));
477 PyTuple_SET_ITEM(result, 2, PyInt_FromLong(fileno));
478 if (s1 == NULL)
479 PyTuple_SET_ITEM(result, 1, PyInt_FromLong(tdelta));
480 else
481 PyTuple_SET_ITEM(result, 1, s1);
482 if (s2 == NULL)
483 PyTuple_SET_ITEM(result, 3, PyInt_FromLong(lineno));
484 else
485 PyTuple_SET_ITEM(result, 3, s2);
487 /* The only other case is err == ERR_EXCEPTION, in which case the
488 * exception is already set.
490 #if 0
491 b0 = self->buffer[self->index];
492 b1 = self->buffer[self->index + 1];
493 if (b0 & 1) {
494 /* This is a line-number event. */
495 what = PyTrace_LINE;
496 lineno = ((b0 & ~1) << 7) + b1;
497 self->index += 2;
499 else {
500 what = (b0 & 0x0E) >> 1;
501 tdelta = ((b0 & 0xF0) << 4) + b1;
502 if (what == PyTrace_CALL) {
503 /* we know there's a 2-byte file ID & 2-byte line number */
504 fileno = ((self->buffer[self->index + 2] << 8)
505 + self->buffer[self->index + 3]);
506 lineno = ((self->buffer[self->index + 4] << 8)
507 + self->buffer[self->index + 5]);
508 self->index += 6;
510 else
511 self->index += 2;
513 #endif
514 return result;
517 static void
518 logreader_dealloc(LogReaderObject *self)
520 if (self->logfp != NULL) {
521 fclose(self->logfp);
522 self->logfp = NULL;
524 Py_XDECREF(self->info);
525 PyObject_Del(self);
528 static PyObject *
529 logreader_sq_item(LogReaderObject *self, int index)
531 PyObject *result = logreader_tp_iternext(self);
532 if (result == NULL && !PyErr_Occurred()) {
533 PyErr_SetString(PyExc_IndexError, "no more events in log");
534 return NULL;
536 return result;
539 static void
540 do_stop(ProfilerObject *self);
542 static int
543 flush_data(ProfilerObject *self)
545 /* Need to dump data to the log file... */
546 size_t written = fwrite(self->buffer, 1, self->index, self->logfp);
547 if (written == (size_t)self->index)
548 self->index = 0;
549 else {
550 memmove(self->buffer, &self->buffer[written],
551 self->index - written);
552 self->index -= written;
553 if (written == 0) {
554 char *s = PyString_AsString(self->logfilename);
555 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
556 do_stop(self);
557 return -1;
560 if (written > 0) {
561 if (fflush(self->logfp)) {
562 char *s = PyString_AsString(self->logfilename);
563 PyErr_SetFromErrnoWithFilename(PyExc_IOError, s);
564 do_stop(self);
565 return -1;
568 return 0;
571 static inline int
572 pack_packed_int(ProfilerObject *self, int value)
574 unsigned char partial;
576 do {
577 partial = value & 0x7F;
578 value >>= 7;
579 if (value)
580 partial |= 0x80;
581 self->buffer[self->index] = partial;
582 self->index++;
583 } while (value);
584 return 0;
587 /* Encode a modified packed integer, with a subfield of modsize bits
588 * containing the value "subfield". The value of subfield is not
589 * checked to ensure it actually fits in modsize bits.
591 static inline int
592 pack_modified_packed_int(ProfilerObject *self, int value,
593 int modsize, int subfield)
595 const int maxvalues[] = {-1, 1, 3, 7, 15, 31, 63, 127};
597 int bits = 7 - modsize;
598 int partial = value & maxvalues[bits];
599 unsigned char b = subfield | (partial << modsize);
601 if (partial != value) {
602 b |= 0x80;
603 self->buffer[self->index] = b;
604 self->index++;
605 return pack_packed_int(self, value >> bits);
607 self->buffer[self->index] = b;
608 self->index++;
609 return 0;
612 static int
613 pack_string(ProfilerObject *self, const char *s, int len)
615 if (len + PISIZE + self->index >= BUFFERSIZE) {
616 if (flush_data(self) < 0)
617 return -1;
619 if (pack_packed_int(self, len) < 0)
620 return -1;
621 memcpy(self->buffer + self->index, s, len);
622 self->index += len;
623 return 0;
626 static int
627 pack_add_info(ProfilerObject *self, const char *s1, const char *s2)
629 int len1 = strlen(s1);
630 int len2 = strlen(s2);
632 if (len1 + len2 + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
633 if (flush_data(self) < 0)
634 return -1;
636 self->buffer[self->index] = WHAT_ADD_INFO;
637 self->index++;
638 if (pack_string(self, s1, len1) < 0)
639 return -1;
640 return pack_string(self, s2, len2);
643 static int
644 pack_define_file(ProfilerObject *self, int fileno, const char *filename)
646 int len = strlen(filename);
648 if (len + PISIZE*2 + 1 + self->index >= BUFFERSIZE) {
649 if (flush_data(self) < 0)
650 return -1;
652 self->buffer[self->index] = WHAT_DEFINE_FILE;
653 self->index++;
654 if (pack_packed_int(self, fileno) < 0)
655 return -1;
656 return pack_string(self, filename, len);
659 static int
660 pack_define_func(ProfilerObject *self, int fileno, int lineno,
661 const char *funcname)
663 int len = strlen(funcname);
665 if (len + PISIZE*3 + 1 + self->index >= BUFFERSIZE) {
666 if (flush_data(self) < 0)
667 return -1;
669 self->buffer[self->index] = WHAT_DEFINE_FUNC;
670 self->index++;
671 if (pack_packed_int(self, fileno) < 0)
672 return -1;
673 if (pack_packed_int(self, lineno) < 0)
674 return -1;
675 return pack_string(self, funcname, len);
678 static int
679 pack_line_times(ProfilerObject *self)
681 if (2 + self->index >= BUFFERSIZE) {
682 if (flush_data(self) < 0)
683 return -1;
685 self->buffer[self->index] = WHAT_LINE_TIMES;
686 self->buffer[self->index + 1] = self->linetimings ? 1 : 0;
687 self->index += 2;
688 return 0;
691 static int
692 pack_frame_times(ProfilerObject *self)
694 if (2 + self->index >= BUFFERSIZE) {
695 if (flush_data(self) < 0)
696 return -1;
698 self->buffer[self->index] = WHAT_FRAME_TIMES;
699 self->buffer[self->index + 1] = self->frametimings ? 1 : 0;
700 self->index += 2;
701 return 0;
704 static inline int
705 pack_enter(ProfilerObject *self, int fileno, int tdelta, int lineno)
707 if (MPISIZE + PISIZE*2 + self->index >= BUFFERSIZE) {
708 if (flush_data(self) < 0)
709 return -1;
711 pack_modified_packed_int(self, fileno, 2, WHAT_ENTER);
712 pack_packed_int(self, lineno);
713 if (self->frametimings)
714 return pack_packed_int(self, tdelta);
715 else
716 return 0;
719 static inline int
720 pack_exit(ProfilerObject *self, int tdelta)
722 if (MPISIZE + self->index >= BUFFERSIZE) {
723 if (flush_data(self) < 0)
724 return -1;
726 if (self->frametimings)
727 return pack_modified_packed_int(self, tdelta, 2, WHAT_EXIT);
728 self->buffer[self->index] = WHAT_EXIT;
729 self->index++;
730 return 0;
733 static inline int
734 pack_lineno(ProfilerObject *self, int lineno)
736 if (MPISIZE + self->index >= BUFFERSIZE) {
737 if (flush_data(self) < 0)
738 return -1;
740 return pack_modified_packed_int(self, lineno, 2, WHAT_LINENO);
743 static inline int
744 pack_lineno_tdelta(ProfilerObject *self, int lineno, int tdelta)
746 if (MPISIZE + PISIZE + self->index >= BUFFERSIZE) {
747 if (flush_data(self) < 0)
748 return 0;
750 if (pack_modified_packed_int(self, lineno, 2, WHAT_LINENO) < 0)
751 return -1;
752 return pack_packed_int(self, tdelta);
755 static inline int
756 get_fileno(ProfilerObject *self, PyCodeObject *fcode)
758 /* This is only used for ENTER events. */
760 PyObject *obj;
761 PyObject *dict;
762 int fileno;
764 obj = PyDict_GetItem(self->filemap, fcode->co_filename);
765 if (obj == NULL) {
766 /* first sighting of this file */
767 dict = PyDict_New();
768 if (dict == NULL) {
769 return -1;
771 fileno = self->next_fileno;
772 obj = Py_BuildValue("iN", fileno, dict);
773 if (obj == NULL) {
774 return -1;
776 if (PyDict_SetItem(self->filemap, fcode->co_filename, obj)) {
777 Py_DECREF(obj);
778 return -1;
780 self->next_fileno++;
781 Py_DECREF(obj);
782 if (pack_define_file(self, fileno,
783 PyString_AS_STRING(fcode->co_filename)) < 0)
784 return -1;
786 else {
787 /* already know this ID */
788 fileno = PyInt_AS_LONG(PyTuple_GET_ITEM(obj, 0));
789 dict = PyTuple_GET_ITEM(obj, 1);
791 /* make sure we save a function name for this (fileno, lineno) */
792 obj = PyInt_FromLong(fcode->co_firstlineno);
793 if (obj == NULL) {
794 /* We just won't have it saved; too bad. */
795 PyErr_Clear();
797 else {
798 PyObject *name = PyDict_GetItem(dict, obj);
799 if (name == NULL) {
800 if (pack_define_func(self, fileno, fcode->co_firstlineno,
801 PyString_AS_STRING(fcode->co_name)) < 0) {
802 Py_DECREF(obj);
803 return -1;
805 if (PyDict_SetItem(dict, obj, fcode->co_name)) {
806 Py_DECREF(obj);
807 return -1;
810 Py_DECREF(obj);
812 return fileno;
815 static inline int
816 get_tdelta(ProfilerObject *self)
818 int tdelta;
819 #ifdef MS_WINDOWS
820 hs_time tv;
821 hs_time diff;
823 GETTIMEOFDAY(&tv);
824 diff = tv - self->prev_timeofday;
825 tdelta = (int)diff;
826 #else
827 struct timeval tv;
829 GETTIMEOFDAY(&tv);
831 tdelta = tv.tv_usec - self->prev_timeofday.tv_usec;
832 if (tv.tv_sec != self->prev_timeofday.tv_sec)
833 tdelta += (tv.tv_sec - self->prev_timeofday.tv_sec) * 1000000;
834 #endif
835 /* time can go backwards on some multiprocessor systems or by NTP */
836 if (tdelta < 0)
837 return 0;
839 self->prev_timeofday = tv;
840 return tdelta;
844 /* The workhorse: the profiler callback function. */
846 static int
847 tracer_callback(ProfilerObject *self, PyFrameObject *frame, int what,
848 PyObject *arg)
850 int fileno;
852 switch (what) {
853 case PyTrace_CALL:
854 fileno = get_fileno(self, frame->f_code);
855 if (fileno < 0)
856 return -1;
857 return pack_enter(self, fileno,
858 self->frametimings ? get_tdelta(self) : -1,
859 frame->f_code->co_firstlineno);
861 case PyTrace_RETURN:
862 return pack_exit(self, get_tdelta(self));
864 case PyTrace_LINE: /* we only get these events if we asked for them */
865 if (self->linetimings)
866 return pack_lineno_tdelta(self, frame->f_lineno,
867 get_tdelta(self));
868 else
869 return pack_lineno(self, frame->f_lineno);
871 default:
872 /* ignore PyTrace_EXCEPTION */
873 break;
875 return 0;
879 /* A couple of useful helper functions. */
881 #ifdef MS_WINDOWS
882 static LARGE_INTEGER frequency = {0, 0};
883 #endif
885 static unsigned long timeofday_diff = 0;
886 static unsigned long rusage_diff = 0;
888 static void
889 calibrate(void)
891 hs_time tv1, tv2;
893 #ifdef MS_WINDOWS
894 hs_time diff;
895 QueryPerformanceFrequency(&frequency);
896 #endif
898 GETTIMEOFDAY(&tv1);
899 while (1) {
900 GETTIMEOFDAY(&tv2);
901 #ifdef MS_WINDOWS
902 diff = tv2 - tv1;
903 if (diff != 0) {
904 timeofday_diff = (unsigned long)diff;
905 break;
907 #else
908 if (tv1.tv_sec != tv2.tv_sec || tv1.tv_usec != tv2.tv_usec) {
909 if (tv1.tv_sec == tv2.tv_sec)
910 timeofday_diff = tv2.tv_usec - tv1.tv_usec;
911 else
912 timeofday_diff = (1000000 - tv1.tv_usec) + tv2.tv_usec;
913 break;
915 #endif
917 #if defined(MS_WINDOWS) || defined(PYOS_OS2) || \
918 defined(__VMS)
919 rusage_diff = -1;
920 #else
922 struct rusage ru1, ru2;
924 getrusage(RUSAGE_SELF, &ru1);
925 while (1) {
926 getrusage(RUSAGE_SELF, &ru2);
927 if (ru1.ru_utime.tv_sec != ru2.ru_utime.tv_sec) {
928 rusage_diff = ((1000000 - ru1.ru_utime.tv_usec)
929 + ru2.ru_utime.tv_usec);
930 break;
932 else if (ru1.ru_utime.tv_usec != ru2.ru_utime.tv_usec) {
933 rusage_diff = ru2.ru_utime.tv_usec - ru1.ru_utime.tv_usec;
934 break;
936 else if (ru1.ru_stime.tv_sec != ru2.ru_stime.tv_sec) {
937 rusage_diff = ((1000000 - ru1.ru_stime.tv_usec)
938 + ru2.ru_stime.tv_usec);
939 break;
941 else if (ru1.ru_stime.tv_usec != ru2.ru_stime.tv_usec) {
942 rusage_diff = ru2.ru_stime.tv_usec - ru1.ru_stime.tv_usec;
943 break;
947 #endif
950 static void
951 do_start(ProfilerObject *self)
953 self->active = 1;
954 GETTIMEOFDAY(&self->prev_timeofday);
955 if (self->lineevents)
956 PyEval_SetTrace((Py_tracefunc) tracer_callback, (PyObject *)self);
957 else
958 PyEval_SetProfile((Py_tracefunc) tracer_callback, (PyObject *)self);
961 static void
962 do_stop(ProfilerObject *self)
964 if (self->active) {
965 self->active = 0;
966 if (self->lineevents)
967 PyEval_SetTrace(NULL, NULL);
968 else
969 PyEval_SetProfile(NULL, NULL);
971 if (self->index > 0) {
972 /* Best effort to dump out any remaining data. */
973 flush_data(self);
977 static int
978 is_available(ProfilerObject *self)
980 if (self->active) {
981 PyErr_SetString(ProfilerError, "profiler already active");
982 return 0;
984 if (self->logfp == NULL) {
985 PyErr_SetString(ProfilerError, "profiler already closed");
986 return 0;
988 return 1;
992 /* Profiler object interface methods. */
994 PyDoc_STRVAR(addinfo__doc__,
995 "addinfo(key, value)\n"
996 "Insert an ADD_INFO record into the log.");
998 static PyObject *
999 profiler_addinfo(ProfilerObject *self, PyObject *args)
1001 PyObject *result = NULL;
1002 char *key, *value;
1004 if (PyArg_ParseTuple(args, "ss:addinfo", &key, &value)) {
1005 if (self->logfp == NULL)
1006 PyErr_SetString(ProfilerError, "profiler already closed");
1007 else {
1008 if (pack_add_info(self, key, value) == 0) {
1009 result = Py_None;
1010 Py_INCREF(result);
1014 return result;
1017 PyDoc_STRVAR(close__doc__,
1018 "close()\n"
1019 "Shut down this profiler and close the log files, even if its active.");
1021 static PyObject *
1022 profiler_close(ProfilerObject *self)
1024 do_stop(self);
1025 if (self->logfp != NULL) {
1026 fclose(self->logfp);
1027 self->logfp = NULL;
1029 Py_INCREF(Py_None);
1030 return Py_None;
1033 #define fileno__doc__ logreader_fileno__doc__
1035 static PyObject *
1036 profiler_fileno(ProfilerObject *self)
1038 if (self->logfp == NULL) {
1039 PyErr_SetString(PyExc_ValueError,
1040 "profiler's file object already closed");
1041 return NULL;
1043 return PyInt_FromLong(fileno(self->logfp));
1046 PyDoc_STRVAR(runcall__doc__,
1047 "runcall(callable[, args[, kw]]) -> callable()\n"
1048 "Profile a specific function call, returning the result of that call.");
1050 static PyObject *
1051 profiler_runcall(ProfilerObject *self, PyObject *args)
1053 PyObject *result = NULL;
1054 PyObject *callargs = NULL;
1055 PyObject *callkw = NULL;
1056 PyObject *callable;
1058 if (PyArg_ParseTuple(args, "O|OO:runcall",
1059 &callable, &callargs, &callkw)) {
1060 if (is_available(self)) {
1061 do_start(self);
1062 result = PyEval_CallObjectWithKeywords(callable, callargs, callkw);
1063 do_stop(self);
1066 return result;
1069 PyDoc_STRVAR(runcode__doc__,
1070 "runcode(code, globals[, locals])\n"
1071 "Execute a code object while collecting profile data. If locals is\n"
1072 "omitted, globals is used for the locals as well.");
1074 static PyObject *
1075 profiler_runcode(ProfilerObject *self, PyObject *args)
1077 PyObject *result = NULL;
1078 PyCodeObject *code;
1079 PyObject *globals;
1080 PyObject *locals = NULL;
1082 if (PyArg_ParseTuple(args, "O!O!|O:runcode",
1083 &PyCode_Type, &code,
1084 &PyDict_Type, &globals,
1085 &locals)) {
1086 if (is_available(self)) {
1087 if (locals == NULL || locals == Py_None)
1088 locals = globals;
1089 else if (!PyDict_Check(locals)) {
1090 PyErr_SetString(PyExc_TypeError,
1091 "locals must be a dictionary or None");
1092 return NULL;
1094 do_start(self);
1095 result = PyEval_EvalCode(code, globals, locals);
1096 do_stop(self);
1097 #if 0
1098 if (!PyErr_Occurred()) {
1099 result = Py_None;
1100 Py_INCREF(result);
1102 #endif
1105 return result;
1108 PyDoc_STRVAR(start__doc__,
1109 "start()\n"
1110 "Install this profiler for the current thread.");
1112 static PyObject *
1113 profiler_start(ProfilerObject *self, PyObject *args)
1115 PyObject *result = NULL;
1117 if (is_available(self)) {
1118 do_start(self);
1119 result = Py_None;
1120 Py_INCREF(result);
1122 return result;
1125 PyDoc_STRVAR(stop__doc__,
1126 "stop()\n"
1127 "Remove this profiler from the current thread.");
1129 static PyObject *
1130 profiler_stop(ProfilerObject *self, PyObject *args)
1132 PyObject *result = NULL;
1134 if (!self->active)
1135 PyErr_SetString(ProfilerError, "profiler not active");
1136 else {
1137 do_stop(self);
1138 result = Py_None;
1139 Py_INCREF(result);
1141 return result;
1145 /* Python API support. */
1147 static void
1148 profiler_dealloc(ProfilerObject *self)
1150 do_stop(self);
1151 if (self->logfp != NULL)
1152 fclose(self->logfp);
1153 Py_XDECREF(self->filemap);
1154 Py_XDECREF(self->logfilename);
1155 PyObject_Del((PyObject *)self);
1158 static PyMethodDef profiler_methods[] = {
1159 {"addinfo", (PyCFunction)profiler_addinfo, METH_VARARGS, addinfo__doc__},
1160 {"close", (PyCFunction)profiler_close, METH_NOARGS, close__doc__},
1161 {"fileno", (PyCFunction)profiler_fileno, METH_NOARGS, fileno__doc__},
1162 {"runcall", (PyCFunction)profiler_runcall, METH_VARARGS, runcall__doc__},
1163 {"runcode", (PyCFunction)profiler_runcode, METH_VARARGS, runcode__doc__},
1164 {"start", (PyCFunction)profiler_start, METH_NOARGS, start__doc__},
1165 {"stop", (PyCFunction)profiler_stop, METH_NOARGS, stop__doc__},
1166 {NULL, NULL}
1169 static PyMemberDef profiler_members[] = {
1170 {"frametimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1171 {"lineevents", T_LONG, offsetof(ProfilerObject, lineevents), READONLY},
1172 {"linetimings", T_LONG, offsetof(ProfilerObject, linetimings), READONLY},
1173 {NULL}
1176 static PyObject *
1177 profiler_get_closed(ProfilerObject *self, void *closure)
1179 PyObject *result = (self->logfp == NULL) ? Py_True : Py_False;
1180 Py_INCREF(result);
1181 return result;
1184 static PyGetSetDef profiler_getsets[] = {
1185 {"closed", (getter)profiler_get_closed, NULL,
1186 PyDoc_STR("True if the profiler's output file has already been closed.")},
1187 {NULL}
1191 PyDoc_STRVAR(profiler_object__doc__,
1192 "High-performance profiler object.\n"
1193 "\n"
1194 "Methods:\n"
1195 "\n"
1196 "close(): Stop the profiler and close the log files.\n"
1197 "fileno(): Returns the file descriptor of the log file.\n"
1198 "runcall(): Run a single function call with profiling enabled.\n"
1199 "runcode(): Execute a code object with profiling enabled.\n"
1200 "start(): Install the profiler and return.\n"
1201 "stop(): Remove the profiler.\n"
1202 "\n"
1203 "Attributes (read-only):\n"
1204 "\n"
1205 "closed: True if the profiler has already been closed.\n"
1206 "frametimings: True if ENTER/EXIT events collect timing information.\n"
1207 "lineevents: True if line events are reported to the profiler.\n"
1208 "linetimings: True if line events collect timing information.");
1210 static PyTypeObject ProfilerType = {
1211 PyObject_HEAD_INIT(NULL)
1212 0, /* ob_size */
1213 "_hotshot.ProfilerType", /* tp_name */
1214 (int) sizeof(ProfilerObject), /* tp_basicsize */
1215 0, /* tp_itemsize */
1216 (destructor)profiler_dealloc, /* tp_dealloc */
1217 0, /* tp_print */
1218 0, /* tp_getattr */
1219 0, /* tp_setattr */
1220 0, /* tp_compare */
1221 0, /* tp_repr */
1222 0, /* tp_as_number */
1223 0, /* tp_as_sequence */
1224 0, /* tp_as_mapping */
1225 0, /* tp_hash */
1226 0, /* tp_call */
1227 0, /* tp_str */
1228 PyObject_GenericGetAttr, /* tp_getattro */
1229 0, /* tp_setattro */
1230 0, /* tp_as_buffer */
1231 Py_TPFLAGS_DEFAULT, /* tp_flags */
1232 profiler_object__doc__, /* tp_doc */
1233 0, /* tp_traverse */
1234 0, /* tp_clear */
1235 0, /* tp_richcompare */
1236 0, /* tp_weaklistoffset */
1237 0, /* tp_iter */
1238 0, /* tp_iternext */
1239 profiler_methods, /* tp_methods */
1240 profiler_members, /* tp_members */
1241 profiler_getsets, /* tp_getset */
1242 0, /* tp_base */
1243 0, /* tp_dict */
1244 0, /* tp_descr_get */
1245 0, /* tp_descr_set */
1249 static PyMethodDef logreader_methods[] = {
1250 {"close", (PyCFunction)logreader_close, METH_NOARGS,
1251 logreader_close__doc__},
1252 {"fileno", (PyCFunction)logreader_fileno, METH_NOARGS,
1253 logreader_fileno__doc__},
1254 {NULL, NULL}
1257 static PyMemberDef logreader_members[] = {
1258 {"info", T_OBJECT, offsetof(LogReaderObject, info), RO,
1259 PyDoc_STR("Dictionary mapping informational keys to lists of values.")},
1260 {NULL}
1264 PyDoc_STRVAR(logreader__doc__,
1265 "logreader(filename) --> log-iterator\n\
1266 Create a log-reader for the timing information file.");
1268 static PySequenceMethods logreader_as_sequence = {
1269 0, /* sq_length */
1270 0, /* sq_concat */
1271 0, /* sq_repeat */
1272 (intargfunc)logreader_sq_item, /* sq_item */
1273 0, /* sq_slice */
1274 0, /* sq_ass_item */
1275 0, /* sq_ass_slice */
1276 0, /* sq_contains */
1277 0, /* sq_inplace_concat */
1278 0, /* sq_inplace_repeat */
1281 static PyObject *
1282 logreader_get_closed(LogReaderObject *self, void *closure)
1284 PyObject *result = (self->logfp == NULL) ? Py_True : Py_False;
1285 Py_INCREF(result);
1286 return result;
1289 static PyGetSetDef logreader_getsets[] = {
1290 {"closed", (getter)logreader_get_closed, NULL,
1291 PyDoc_STR("True if the logreader's input file has already been closed.")},
1292 {NULL}
1295 static PyTypeObject LogReaderType = {
1296 PyObject_HEAD_INIT(NULL)
1297 0, /* ob_size */
1298 "_hotshot.LogReaderType", /* tp_name */
1299 (int) sizeof(LogReaderObject), /* tp_basicsize */
1300 0, /* tp_itemsize */
1301 (destructor)logreader_dealloc, /* tp_dealloc */
1302 0, /* tp_print */
1303 0, /* tp_getattr */
1304 0, /* tp_setattr */
1305 0, /* tp_compare */
1306 0, /* tp_repr */
1307 0, /* tp_as_number */
1308 &logreader_as_sequence, /* tp_as_sequence */
1309 0, /* tp_as_mapping */
1310 0, /* tp_hash */
1311 0, /* tp_call */
1312 0, /* tp_str */
1313 PyObject_GenericGetAttr, /* tp_getattro */
1314 0, /* tp_setattro */
1315 0, /* tp_as_buffer */
1316 Py_TPFLAGS_DEFAULT, /* tp_flags */
1317 logreader__doc__, /* tp_doc */
1318 0, /* tp_traverse */
1319 0, /* tp_clear */
1320 0, /* tp_richcompare */
1321 0, /* tp_weaklistoffset */
1322 PyObject_SelfIter, /* tp_iter */
1323 (iternextfunc)logreader_tp_iternext,/* tp_iternext */
1324 logreader_methods, /* tp_methods */
1325 logreader_members, /* tp_members */
1326 logreader_getsets, /* tp_getset */
1327 0, /* tp_base */
1328 0, /* tp_dict */
1329 0, /* tp_descr_get */
1330 0, /* tp_descr_set */
1333 static PyObject *
1334 hotshot_logreader(PyObject *unused, PyObject *args)
1336 LogReaderObject *self = NULL;
1337 char *filename;
1338 int c;
1339 int err = 0;
1341 if (PyArg_ParseTuple(args, "s:logreader", &filename)) {
1342 self = PyObject_New(LogReaderObject, &LogReaderType);
1343 if (self != NULL) {
1344 self->frametimings = 1;
1345 self->linetimings = 0;
1346 self->info = NULL;
1347 self->logfp = fopen(filename, "rb");
1348 if (self->logfp == NULL) {
1349 PyErr_SetFromErrnoWithFilename(PyExc_IOError, filename);
1350 Py_DECREF(self);
1351 self = NULL;
1352 goto finally;
1354 self->info = PyDict_New();
1355 if (self->info == NULL) {
1356 Py_DECREF(self);
1357 goto finally;
1359 /* read initial info */
1360 for (;;) {
1361 if ((c = fgetc(self->logfp)) == EOF) {
1362 eof_error(self);
1363 break;
1365 if (c != WHAT_ADD_INFO) {
1366 ungetc(c, self->logfp);
1367 break;
1369 err = unpack_add_info(self);
1370 if (err) {
1371 if (err == ERR_EOF)
1372 eof_error(self);
1373 else
1374 PyErr_SetString(PyExc_RuntimeError,
1375 "unexpected error");
1376 break;
1381 finally:
1382 return (PyObject *) self;
1386 /* Return a Python string that represents the version number without the
1387 * extra cruft added by revision control, even if the right options were
1388 * given to the "cvs export" command to make it not include the extra
1389 * cruft.
1391 static char *
1392 get_version_string(void)
1394 static char *rcsid = "$Revision$";
1395 char *rev = rcsid;
1396 char *buffer;
1397 int i = 0;
1399 while (*rev && !isdigit(Py_CHARMASK(*rev)))
1400 ++rev;
1401 while (rev[i] != ' ' && rev[i] != '\0')
1402 ++i;
1403 buffer = malloc(i + 1);
1404 if (buffer != NULL) {
1405 memmove(buffer, rev, i);
1406 buffer[i] = '\0';
1408 return buffer;
1411 /* Write out a RFC 822-style header with various useful bits of
1412 * information to make the output easier to manage.
1414 static int
1415 write_header(ProfilerObject *self)
1417 char *buffer;
1418 char cwdbuffer[PATH_MAX];
1419 PyObject *temp;
1420 int i, len;
1422 buffer = get_version_string();
1423 if (buffer == NULL) {
1424 PyErr_NoMemory();
1425 return -1;
1427 pack_add_info(self, "hotshot-version", buffer);
1428 pack_add_info(self, "requested-frame-timings",
1429 (self->frametimings ? "yes" : "no"));
1430 pack_add_info(self, "requested-line-events",
1431 (self->lineevents ? "yes" : "no"));
1432 pack_add_info(self, "requested-line-timings",
1433 (self->linetimings ? "yes" : "no"));
1434 pack_add_info(self, "platform", Py_GetPlatform());
1435 pack_add_info(self, "executable", Py_GetProgramFullPath());
1436 free(buffer);
1437 buffer = (char *) Py_GetVersion();
1438 if (buffer == NULL)
1439 PyErr_Clear();
1440 else
1441 pack_add_info(self, "executable-version", buffer);
1443 #ifdef MS_WINDOWS
1444 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%I64d", frequency.QuadPart);
1445 pack_add_info(self, "reported-performance-frequency", cwdbuffer);
1446 #else
1447 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", rusage_diff);
1448 pack_add_info(self, "observed-interval-getrusage", cwdbuffer);
1449 PyOS_snprintf(cwdbuffer, sizeof(cwdbuffer), "%lu", timeofday_diff);
1450 pack_add_info(self, "observed-interval-gettimeofday", cwdbuffer);
1451 #endif
1453 pack_add_info(self, "current-directory",
1454 getcwd(cwdbuffer, sizeof cwdbuffer));
1456 temp = PySys_GetObject("path");
1457 len = PyList_GET_SIZE(temp);
1458 for (i = 0; i < len; ++i) {
1459 PyObject *item = PyList_GET_ITEM(temp, i);
1460 buffer = PyString_AsString(item);
1461 if (buffer == NULL) {
1462 pack_add_info(self, "sys-path-entry", "<non-string-path-entry>");
1463 PyErr_Clear();
1465 else {
1466 pack_add_info(self, "sys-path-entry", buffer);
1469 pack_frame_times(self);
1470 pack_line_times(self);
1472 return 0;
1475 PyDoc_STRVAR(profiler__doc__,
1476 "profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1477 Create a new profiler object.");
1479 static PyObject *
1480 hotshot_profiler(PyObject *unused, PyObject *args)
1482 char *logfilename;
1483 ProfilerObject *self = NULL;
1484 int lineevents = 0;
1485 int linetimings = 1;
1487 if (PyArg_ParseTuple(args, "s|ii:profiler", &logfilename,
1488 &lineevents, &linetimings)) {
1489 self = PyObject_New(ProfilerObject, &ProfilerType);
1490 if (self == NULL)
1491 return NULL;
1492 self->frametimings = 1;
1493 self->lineevents = lineevents ? 1 : 0;
1494 self->linetimings = (lineevents && linetimings) ? 1 : 0;
1495 self->index = 0;
1496 self->active = 0;
1497 self->next_fileno = 0;
1498 self->logfp = NULL;
1499 self->logfilename = PyTuple_GET_ITEM(args, 0);
1500 Py_INCREF(self->logfilename);
1501 self->filemap = PyDict_New();
1502 if (self->filemap == NULL) {
1503 Py_DECREF(self);
1504 return NULL;
1506 self->logfp = fopen(logfilename, "wb");
1507 if (self->logfp == NULL) {
1508 Py_DECREF(self);
1509 PyErr_SetFromErrnoWithFilename(PyExc_IOError, logfilename);
1510 return NULL;
1512 if (timeofday_diff == 0) {
1513 /* Run this several times since sometimes the first
1514 * doesn't give the lowest values, and we're really trying
1515 * to determine the lowest.
1517 calibrate();
1518 calibrate();
1519 calibrate();
1521 if (write_header(self))
1522 /* some error occurred, exception has been set */
1523 self = NULL;
1525 return (PyObject *) self;
1528 PyDoc_STRVAR(coverage__doc__,
1529 "coverage(logfilename) -> profiler\n\
1530 Returns a profiler that doesn't collect any timing information, which is\n\
1531 useful in building a coverage analysis tool.");
1533 static PyObject *
1534 hotshot_coverage(PyObject *unused, PyObject *args)
1536 char *logfilename;
1537 PyObject *result = NULL;
1539 if (PyArg_ParseTuple(args, "s:coverage", &logfilename)) {
1540 result = hotshot_profiler(unused, args);
1541 if (result != NULL) {
1542 ProfilerObject *self = (ProfilerObject *) result;
1543 self->frametimings = 0;
1544 self->linetimings = 0;
1545 self->lineevents = 1;
1548 return result;
1551 PyDoc_VAR(resolution__doc__) =
1552 #ifdef MS_WINDOWS
1553 PyDoc_STR(
1554 "resolution() -> (performance-counter-ticks, update-frequency)\n"
1555 "Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1556 "function. The first value is the smallest observed change, and the second\n"
1557 "is the result of QueryPerformanceFrequency()."
1559 #else
1560 PyDoc_STR(
1561 "resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1562 "Return the resolution of the timers provided by the gettimeofday() and\n"
1563 "getrusage() system calls, or -1 if the call is not supported."
1565 #endif
1568 static PyObject *
1569 hotshot_resolution(PyObject *unused, PyObject *args)
1571 PyObject *result = NULL;
1573 if (PyArg_ParseTuple(args, ":resolution")) {
1574 if (timeofday_diff == 0) {
1575 calibrate();
1576 calibrate();
1577 calibrate();
1579 #ifdef MS_WINDOWS
1580 result = Py_BuildValue("ii", timeofday_diff, frequency.LowPart);
1581 #else
1582 result = Py_BuildValue("ii", timeofday_diff, rusage_diff);
1583 #endif
1585 return result;
1589 static PyMethodDef functions[] = {
1590 {"coverage", hotshot_coverage, METH_VARARGS, coverage__doc__},
1591 {"profiler", hotshot_profiler, METH_VARARGS, profiler__doc__},
1592 {"logreader", hotshot_logreader, METH_VARARGS, logreader__doc__},
1593 {"resolution", hotshot_resolution, METH_VARARGS, resolution__doc__},
1594 {NULL, NULL}
1598 void
1599 init_hotshot(void)
1601 PyObject *module;
1603 LogReaderType.ob_type = &PyType_Type;
1604 ProfilerType.ob_type = &PyType_Type;
1605 module = Py_InitModule("_hotshot", functions);
1606 if (module != NULL) {
1607 char *s = get_version_string();
1609 PyModule_AddStringConstant(module, "__version__", s);
1610 free(s);
1611 Py_INCREF(&LogReaderType);
1612 PyModule_AddObject(module, "LogReaderType",
1613 (PyObject *)&LogReaderType);
1614 Py_INCREF(&ProfilerType);
1615 PyModule_AddObject(module, "ProfilerType",
1616 (PyObject *)&ProfilerType);
1618 if (ProfilerError == NULL)
1619 ProfilerError = PyErr_NewException("hotshot.ProfilerError",
1620 NULL, NULL);
1621 if (ProfilerError != NULL) {
1622 Py_INCREF(ProfilerError);
1623 PyModule_AddObject(module, "ProfilerError", ProfilerError);
1625 PyModule_AddIntConstant(module, "WHAT_ENTER", WHAT_ENTER);
1626 PyModule_AddIntConstant(module, "WHAT_EXIT", WHAT_EXIT);
1627 PyModule_AddIntConstant(module, "WHAT_LINENO", WHAT_LINENO);
1628 PyModule_AddIntConstant(module, "WHAT_OTHER", WHAT_OTHER);
1629 PyModule_AddIntConstant(module, "WHAT_ADD_INFO", WHAT_ADD_INFO);
1630 PyModule_AddIntConstant(module, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE);
1631 PyModule_AddIntConstant(module, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC);
1632 PyModule_AddIntConstant(module, "WHAT_LINE_TIMES", WHAT_LINE_TIMES);