2 * This is the High Performance Python Profiler portion of HotShot.
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.
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; }
26 #ifndef HAVE_GETTIMEOFDAY
27 #error "This module requires gettimeofday() on non-Windows platforms!"
29 #if (defined(PYOS_OS2) && defined(PYCC_GCC))
32 #include <sys/resource.h>
33 #include <sys/times.h>
35 typedef struct timeval hs_time
;
38 #if !defined(__cplusplus) && !defined(inline)
40 #define inline __inline
48 #define BUFFERSIZE 10240
50 #if defined(PYOS_OS2) && defined(PYCC_GCC)
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) */
62 # define PATH_MAX MAX_PATH
63 # elif defined (_POSIX_PATH_MAX)
64 # define PATH_MAX _POSIX_PATH_MAX
66 # error "Need a defn. for PATH_MAX in _hotshot.c"
73 PyObject
*logfilename
;
75 unsigned char buffer
[BUFFERSIZE
];
83 hs_time prev_timeofday
;
94 static PyObject
* ProfilerError
= NULL
;
98 #ifdef GETTIMEOFDAY_NO_TZ
99 #define GETTIMEOFDAY(ptv) gettimeofday((ptv))
101 #define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
106 /* The log reader... */
108 PyDoc_STRVAR(logreader_close__doc__
,
110 "Close the log file, preventing additional records from being read.");
113 logreader_close(LogReaderObject
*self
, PyObject
*args
)
115 if (self
->logfp
!= NULL
) {
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.");
130 logreader_fileno(LogReaderObject
*self
)
132 if (self
->logfp
== NULL
) {
133 PyErr_SetString(PyExc_ValueError
,
134 "logreader's file object already closed");
137 return PyInt_FromLong(fileno(self
->logfp
));
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"
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
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.
188 * MPI(2,type) fileno -- type is 0x00
190 * PI tdelta -- iff frame times are enabled
194 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
195 * if frame times are disabled
199 * MPI(2,type) lineno -- type is 0x02
200 * PI tdelta -- iff LINENO includes it
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
214 * PI len -- length of filename
215 * BYTE filename[len] -- len bytes of string data
217 * DEFINE_FUNC records
219 * BYTE type -- always 0x43
222 * PI len -- length of funcname
223 * BYTE funcname[len] -- len bytes of string data
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
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
243 * BYTE type -- always 0x53
244 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
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
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.
274 unpack_packed_int(LogReaderObject
*self
, int *pvalue
, int discard
)
283 if ((c
= fgetc(self
->logfp
)) == EOF
)
285 accum
|= ((c
& 0x7F) >> discard
) << bits
;
286 bits
+= (7 - discard
);
296 /* Unpack a string, which is encoded as a packed integer giving the
297 * length of the string, followed by the string data.
300 unpack_string(LogReaderObject
*self
, PyObject
**pvalue
)
308 if ((err
= unpack_packed_int(self
, &len
, 0)))
312 for (i
=0; i
< len
; i
++) {
313 ch
= fgetc(self
->logfp
);
320 *pvalue
= PyString_FromStringAndSize(buf
, len
);
322 if (*pvalue
== NULL
) {
323 return ERR_EXCEPTION
;
330 unpack_add_info(LogReaderObject
*self
)
333 PyObject
*value
= NULL
;
336 err
= unpack_string(self
, &key
);
338 err
= unpack_string(self
, &value
);
342 PyObject
*list
= PyDict_GetItem(self
->info
, key
);
344 list
= PyList_New(0);
349 if (PyDict_SetItem(self
->info
, key
, list
)) {
356 if (PyList_Append(list
, value
))
368 eof_error(LogReaderObject
*self
)
372 PyErr_SetString(PyExc_EOFError
,
373 "end of file with incomplete profile record");
377 logreader_tp_iternext(LogReaderObject
*self
)
385 PyObject
*s1
= NULL
, *s2
= NULL
;
386 PyObject
*result
= NULL
;
388 unsigned char b0
, b1
;
391 if (self
->logfp
== NULL
) {
392 PyErr_SetString(ProfilerError
,
393 "cannot iterate over closed LogReader object");
398 /* decode the record type */
399 if ((c
= fgetc(self
->logfp
)) == EOF
) {
404 what
= c
& WHAT_OTHER
;
405 if (what
== WHAT_OTHER
)
406 what
= c
; /* need all the bits for type */
408 ungetc(c
, self
->logfp
); /* type byte includes packed int */
412 err
= unpack_packed_int(self
, &fileno
, 2);
414 err
= unpack_packed_int(self
, &lineno
, 0);
415 if (self
->frametimings
&& !err
)
416 err
= unpack_packed_int(self
, &tdelta
, 0);
420 err
= unpack_packed_int(self
, &tdelta
, 2);
423 err
= unpack_packed_int(self
, &lineno
, 2);
424 if (self
->linetimings
&& !err
)
425 err
= unpack_packed_int(self
, &tdelta
, 0);
428 err
= unpack_add_info(self
);
430 case WHAT_DEFINE_FILE
:
431 err
= unpack_packed_int(self
, &fileno
, 0);
433 err
= unpack_string(self
, &s1
);
440 case WHAT_DEFINE_FUNC
:
441 err
= unpack_packed_int(self
, &fileno
, 0);
443 err
= unpack_packed_int(self
, &lineno
, 0);
445 err
= unpack_string(self
, &s1
);
448 case WHAT_LINE_TIMES
:
449 if ((c
= fgetc(self
->logfp
)) == EOF
)
452 self
->linetimings
= c
? 1 : 0;
456 case WHAT_FRAME_TIMES
:
457 if ((c
= fgetc(self
->logfp
)) == EOF
)
460 self
->frametimings
= c
? 1 : 0;
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
) {
475 result
= PyTuple_New(4);
476 PyTuple_SET_ITEM(result
, 0, PyInt_FromLong(what
));
477 PyTuple_SET_ITEM(result
, 2, PyInt_FromLong(fileno
));
479 PyTuple_SET_ITEM(result
, 1, PyInt_FromLong(tdelta
));
481 PyTuple_SET_ITEM(result
, 1, s1
);
483 PyTuple_SET_ITEM(result
, 3, PyInt_FromLong(lineno
));
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.
491 b0
= self
->buffer
[self
->index
];
492 b1
= self
->buffer
[self
->index
+ 1];
494 /* This is a line-number event. */
496 lineno
= ((b0
& ~1) << 7) + b1
;
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]);
518 logreader_dealloc(LogReaderObject
*self
)
520 if (self
->logfp
!= NULL
) {
524 Py_XDECREF(self
->info
);
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");
540 do_stop(ProfilerObject
*self
);
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
)
550 memmove(self
->buffer
, &self
->buffer
[written
],
551 self
->index
- written
);
552 self
->index
-= written
;
554 char *s
= PyString_AsString(self
->logfilename
);
555 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, s
);
561 if (fflush(self
->logfp
)) {
562 char *s
= PyString_AsString(self
->logfilename
);
563 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, s
);
572 pack_packed_int(ProfilerObject
*self
, int value
)
574 unsigned char partial
;
577 partial
= value
& 0x7F;
581 self
->buffer
[self
->index
] = partial
;
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.
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
) {
603 self
->buffer
[self
->index
] = b
;
605 return pack_packed_int(self
, value
>> bits
);
607 self
->buffer
[self
->index
] = b
;
613 pack_string(ProfilerObject
*self
, const char *s
, int len
)
615 if (len
+ PISIZE
+ self
->index
>= BUFFERSIZE
) {
616 if (flush_data(self
) < 0)
619 if (pack_packed_int(self
, len
) < 0)
621 memcpy(self
->buffer
+ self
->index
, s
, len
);
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)
636 self
->buffer
[self
->index
] = WHAT_ADD_INFO
;
638 if (pack_string(self
, s1
, len1
) < 0)
640 return pack_string(self
, s2
, len2
);
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)
652 self
->buffer
[self
->index
] = WHAT_DEFINE_FILE
;
654 if (pack_packed_int(self
, fileno
) < 0)
656 return pack_string(self
, filename
, len
);
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)
669 self
->buffer
[self
->index
] = WHAT_DEFINE_FUNC
;
671 if (pack_packed_int(self
, fileno
) < 0)
673 if (pack_packed_int(self
, lineno
) < 0)
675 return pack_string(self
, funcname
, len
);
679 pack_line_times(ProfilerObject
*self
)
681 if (2 + self
->index
>= BUFFERSIZE
) {
682 if (flush_data(self
) < 0)
685 self
->buffer
[self
->index
] = WHAT_LINE_TIMES
;
686 self
->buffer
[self
->index
+ 1] = self
->linetimings
? 1 : 0;
692 pack_frame_times(ProfilerObject
*self
)
694 if (2 + self
->index
>= BUFFERSIZE
) {
695 if (flush_data(self
) < 0)
698 self
->buffer
[self
->index
] = WHAT_FRAME_TIMES
;
699 self
->buffer
[self
->index
+ 1] = self
->frametimings
? 1 : 0;
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)
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
);
720 pack_exit(ProfilerObject
*self
, int tdelta
)
722 if (MPISIZE
+ self
->index
>= BUFFERSIZE
) {
723 if (flush_data(self
) < 0)
726 if (self
->frametimings
)
727 return pack_modified_packed_int(self
, tdelta
, 2, WHAT_EXIT
);
728 self
->buffer
[self
->index
] = WHAT_EXIT
;
734 pack_lineno(ProfilerObject
*self
, int lineno
)
736 if (MPISIZE
+ self
->index
>= BUFFERSIZE
) {
737 if (flush_data(self
) < 0)
740 return pack_modified_packed_int(self
, lineno
, 2, WHAT_LINENO
);
744 pack_lineno_tdelta(ProfilerObject
*self
, int lineno
, int tdelta
)
746 if (MPISIZE
+ PISIZE
+ self
->index
>= BUFFERSIZE
) {
747 if (flush_data(self
) < 0)
750 if (pack_modified_packed_int(self
, lineno
, 2, WHAT_LINENO
) < 0)
752 return pack_packed_int(self
, tdelta
);
756 get_fileno(ProfilerObject
*self
, PyCodeObject
*fcode
)
758 /* This is only used for ENTER events. */
764 obj
= PyDict_GetItem(self
->filemap
, fcode
->co_filename
);
766 /* first sighting of this file */
771 fileno
= self
->next_fileno
;
772 obj
= Py_BuildValue("iN", fileno
, dict
);
776 if (PyDict_SetItem(self
->filemap
, fcode
->co_filename
, obj
)) {
782 if (pack_define_file(self
, fileno
,
783 PyString_AS_STRING(fcode
->co_filename
)) < 0)
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
);
794 /* We just won't have it saved; too bad. */
798 PyObject
*name
= PyDict_GetItem(dict
, obj
);
800 if (pack_define_func(self
, fileno
, fcode
->co_firstlineno
,
801 PyString_AS_STRING(fcode
->co_name
)) < 0) {
805 if (PyDict_SetItem(dict
, obj
, fcode
->co_name
)) {
816 get_tdelta(ProfilerObject
*self
)
824 diff
= tv
- self
->prev_timeofday
;
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;
835 /* time can go backwards on some multiprocessor systems or by NTP */
839 self
->prev_timeofday
= tv
;
844 /* The workhorse: the profiler callback function. */
847 tracer_callback(ProfilerObject
*self
, PyFrameObject
*frame
, int what
,
854 fileno
= get_fileno(self
, frame
->f_code
);
857 return pack_enter(self
, fileno
,
858 self
->frametimings
? get_tdelta(self
) : -1,
859 frame
->f_code
->co_firstlineno
);
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
,
869 return pack_lineno(self
, frame
->f_lineno
);
872 /* ignore PyTrace_EXCEPTION */
879 /* A couple of useful helper functions. */
882 static LARGE_INTEGER frequency
= {0, 0};
885 static unsigned long timeofday_diff
= 0;
886 static unsigned long rusage_diff
= 0;
895 QueryPerformanceFrequency(&frequency
);
904 timeofday_diff
= (unsigned long)diff
;
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
;
912 timeofday_diff
= (1000000 - tv1
.tv_usec
) + tv2
.tv_usec
;
917 #if defined(MS_WINDOWS) || defined(PYOS_OS2) || \
922 struct rusage ru1
, ru2
;
924 getrusage(RUSAGE_SELF
, &ru1
);
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
);
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
;
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
);
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
;
951 do_start(ProfilerObject
*self
)
954 GETTIMEOFDAY(&self
->prev_timeofday
);
955 if (self
->lineevents
)
956 PyEval_SetTrace((Py_tracefunc
) tracer_callback
, (PyObject
*)self
);
958 PyEval_SetProfile((Py_tracefunc
) tracer_callback
, (PyObject
*)self
);
962 do_stop(ProfilerObject
*self
)
966 if (self
->lineevents
)
967 PyEval_SetTrace(NULL
, NULL
);
969 PyEval_SetProfile(NULL
, NULL
);
971 if (self
->index
> 0) {
972 /* Best effort to dump out any remaining data. */
978 is_available(ProfilerObject
*self
)
981 PyErr_SetString(ProfilerError
, "profiler already active");
984 if (self
->logfp
== NULL
) {
985 PyErr_SetString(ProfilerError
, "profiler already closed");
992 /* Profiler object interface methods. */
994 PyDoc_STRVAR(addinfo__doc__
,
995 "addinfo(key, value)\n"
996 "Insert an ADD_INFO record into the log.");
999 profiler_addinfo(ProfilerObject
*self
, PyObject
*args
)
1001 PyObject
*result
= NULL
;
1004 if (PyArg_ParseTuple(args
, "ss:addinfo", &key
, &value
)) {
1005 if (self
->logfp
== NULL
)
1006 PyErr_SetString(ProfilerError
, "profiler already closed");
1008 if (pack_add_info(self
, key
, value
) == 0) {
1017 PyDoc_STRVAR(close__doc__
,
1019 "Shut down this profiler and close the log files, even if its active.");
1022 profiler_close(ProfilerObject
*self
)
1025 if (self
->logfp
!= NULL
) {
1026 fclose(self
->logfp
);
1033 #define fileno__doc__ logreader_fileno__doc__
1036 profiler_fileno(ProfilerObject
*self
)
1038 if (self
->logfp
== NULL
) {
1039 PyErr_SetString(PyExc_ValueError
,
1040 "profiler's file object already closed");
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.");
1051 profiler_runcall(ProfilerObject
*self
, PyObject
*args
)
1053 PyObject
*result
= NULL
;
1054 PyObject
*callargs
= NULL
;
1055 PyObject
*callkw
= NULL
;
1058 if (PyArg_ParseTuple(args
, "O|OO:runcall",
1059 &callable
, &callargs
, &callkw
)) {
1060 if (is_available(self
)) {
1062 result
= PyEval_CallObjectWithKeywords(callable
, callargs
, callkw
);
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.");
1075 profiler_runcode(ProfilerObject
*self
, PyObject
*args
)
1077 PyObject
*result
= NULL
;
1080 PyObject
*locals
= NULL
;
1082 if (PyArg_ParseTuple(args
, "O!O!|O:runcode",
1083 &PyCode_Type
, &code
,
1084 &PyDict_Type
, &globals
,
1086 if (is_available(self
)) {
1087 if (locals
== NULL
|| locals
== Py_None
)
1089 else if (!PyDict_Check(locals
)) {
1090 PyErr_SetString(PyExc_TypeError
,
1091 "locals must be a dictionary or None");
1095 result
= PyEval_EvalCode(code
, globals
, locals
);
1098 if (!PyErr_Occurred()) {
1108 PyDoc_STRVAR(start__doc__
,
1110 "Install this profiler for the current thread.");
1113 profiler_start(ProfilerObject
*self
, PyObject
*args
)
1115 PyObject
*result
= NULL
;
1117 if (is_available(self
)) {
1125 PyDoc_STRVAR(stop__doc__
,
1127 "Remove this profiler from the current thread.");
1130 profiler_stop(ProfilerObject
*self
, PyObject
*args
)
1132 PyObject
*result
= NULL
;
1135 PyErr_SetString(ProfilerError
, "profiler not active");
1145 /* Python API support. */
1148 profiler_dealloc(ProfilerObject
*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__
},
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
},
1177 profiler_get_closed(ProfilerObject
*self
, void *closure
)
1179 PyObject
*result
= (self
->logfp
== NULL
) ? Py_True
: Py_False
;
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.")},
1191 PyDoc_STRVAR(profiler_object__doc__
,
1192 "High-performance profiler object.\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"
1203 "Attributes (read-only):\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
)
1213 "_hotshot.ProfilerType", /* tp_name */
1214 (int) sizeof(ProfilerObject
), /* tp_basicsize */
1215 0, /* tp_itemsize */
1216 (destructor
)profiler_dealloc
, /* tp_dealloc */
1222 0, /* tp_as_number */
1223 0, /* tp_as_sequence */
1224 0, /* tp_as_mapping */
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 */
1235 0, /* tp_richcompare */
1236 0, /* tp_weaklistoffset */
1238 0, /* tp_iternext */
1239 profiler_methods
, /* tp_methods */
1240 profiler_members
, /* tp_members */
1241 profiler_getsets
, /* tp_getset */
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__
},
1257 static PyMemberDef logreader_members
[] = {
1258 {"info", T_OBJECT
, offsetof(LogReaderObject
, info
), RO
,
1259 PyDoc_STR("Dictionary mapping informational keys to lists of values.")},
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
= {
1272 (intargfunc
)logreader_sq_item
, /* sq_item */
1274 0, /* sq_ass_item */
1275 0, /* sq_ass_slice */
1276 0, /* sq_contains */
1277 0, /* sq_inplace_concat */
1278 0, /* sq_inplace_repeat */
1282 logreader_get_closed(LogReaderObject
*self
, void *closure
)
1284 PyObject
*result
= (self
->logfp
== NULL
) ? Py_True
: Py_False
;
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.")},
1295 static PyTypeObject LogReaderType
= {
1296 PyObject_HEAD_INIT(NULL
)
1298 "_hotshot.LogReaderType", /* tp_name */
1299 (int) sizeof(LogReaderObject
), /* tp_basicsize */
1300 0, /* tp_itemsize */
1301 (destructor
)logreader_dealloc
, /* tp_dealloc */
1307 0, /* tp_as_number */
1308 &logreader_as_sequence
, /* tp_as_sequence */
1309 0, /* tp_as_mapping */
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 */
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 */
1329 0, /* tp_descr_get */
1330 0, /* tp_descr_set */
1334 hotshot_logreader(PyObject
*unused
, PyObject
*args
)
1336 LogReaderObject
*self
= NULL
;
1341 if (PyArg_ParseTuple(args
, "s:logreader", &filename
)) {
1342 self
= PyObject_New(LogReaderObject
, &LogReaderType
);
1344 self
->frametimings
= 1;
1345 self
->linetimings
= 0;
1347 self
->logfp
= fopen(filename
, "rb");
1348 if (self
->logfp
== NULL
) {
1349 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
1354 self
->info
= PyDict_New();
1355 if (self
->info
== NULL
) {
1359 /* read initial info */
1361 if ((c
= fgetc(self
->logfp
)) == EOF
) {
1365 if (c
!= WHAT_ADD_INFO
) {
1366 ungetc(c
, self
->logfp
);
1369 err
= unpack_add_info(self
);
1374 PyErr_SetString(PyExc_RuntimeError
,
1375 "unexpected error");
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
1392 get_version_string(void)
1394 static char *rcsid
= "$Revision$";
1399 while (*rev
&& !isdigit(Py_CHARMASK(*rev
)))
1401 while (rev
[i
] != ' ' && rev
[i
] != '\0')
1403 buffer
= malloc(i
+ 1);
1404 if (buffer
!= NULL
) {
1405 memmove(buffer
, rev
, i
);
1411 /* Write out a RFC 822-style header with various useful bits of
1412 * information to make the output easier to manage.
1415 write_header(ProfilerObject
*self
)
1418 char cwdbuffer
[PATH_MAX
];
1422 buffer
= get_version_string();
1423 if (buffer
== NULL
) {
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());
1437 buffer
= (char *) Py_GetVersion();
1441 pack_add_info(self
, "executable-version", buffer
);
1444 PyOS_snprintf(cwdbuffer
, sizeof(cwdbuffer
), "%I64d", frequency
.QuadPart
);
1445 pack_add_info(self
, "reported-performance-frequency", cwdbuffer
);
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
);
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>");
1466 pack_add_info(self
, "sys-path-entry", buffer
);
1469 pack_frame_times(self
);
1470 pack_line_times(self
);
1475 PyDoc_STRVAR(profiler__doc__
,
1476 "profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1477 Create a new profiler object.");
1480 hotshot_profiler(PyObject
*unused
, PyObject
*args
)
1483 ProfilerObject
*self
= NULL
;
1485 int linetimings
= 1;
1487 if (PyArg_ParseTuple(args
, "s|ii:profiler", &logfilename
,
1488 &lineevents
, &linetimings
)) {
1489 self
= PyObject_New(ProfilerObject
, &ProfilerType
);
1492 self
->frametimings
= 1;
1493 self
->lineevents
= lineevents
? 1 : 0;
1494 self
->linetimings
= (lineevents
&& linetimings
) ? 1 : 0;
1497 self
->next_fileno
= 0;
1499 self
->logfilename
= PyTuple_GET_ITEM(args
, 0);
1500 Py_INCREF(self
->logfilename
);
1501 self
->filemap
= PyDict_New();
1502 if (self
->filemap
== NULL
) {
1506 self
->logfp
= fopen(logfilename
, "wb");
1507 if (self
->logfp
== NULL
) {
1509 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, logfilename
);
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.
1521 if (write_header(self
))
1522 /* some error occurred, exception has been set */
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.");
1534 hotshot_coverage(PyObject
*unused
, PyObject
*args
)
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;
1551 PyDoc_VAR(resolution__doc__
) =
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()."
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."
1569 hotshot_resolution(PyObject
*unused
, PyObject
*args
)
1571 PyObject
*result
= NULL
;
1573 if (PyArg_ParseTuple(args
, ":resolution")) {
1574 if (timeofday_diff
== 0) {
1580 result
= Py_BuildValue("ii", timeofday_diff
, frequency
.LowPart
);
1582 result
= Py_BuildValue("ii", timeofday_diff
, rusage_diff
);
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__
},
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
);
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",
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
);