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.
18 #include <direct.h> /* for getcwd() */
19 typedef __int64 hs_time
;
20 #define GETTIMEOFDAY(P_HS_TIME) \
21 { LARGE_INTEGER _temp; \
22 QueryPerformanceCounter(&_temp); \
23 *(P_HS_TIME) = _temp.QuadPart; }
27 #ifndef HAVE_GETTIMEOFDAY
28 #error "This module requires gettimeofday() on non-Windows platforms!"
33 #include <sys/resource.h>
34 #include <sys/times.h>
36 typedef struct timeval hs_time
;
39 #if !defined(__cplusplus) && !defined(inline)
41 #define inline __inline
49 #define BUFFERSIZE 10240
57 # define PATH_MAX MAX_PATH
59 # error "Need a defn. for PATH_MAX in _hotshot.c"
66 PyObject
*logfilename
;
68 unsigned char buffer
[BUFFERSIZE
];
76 hs_time prev_timeofday
;
87 unsigned char buffer
[BUFFERSIZE
];
90 static PyObject
* ProfilerError
= NULL
;
94 #ifdef GETTIMEOFDAY_NO_TZ
95 #define GETTIMEOFDAY(ptv) gettimeofday((ptv))
97 #define GETTIMEOFDAY(ptv) gettimeofday((ptv), (struct timezone *)NULL)
102 /* The log reader... */
104 static char logreader_close__doc__
[] =
106 "Close the log file, preventing additional records from being read.";
109 logreader_close(LogReaderObject
*self
, PyObject
*args
)
111 PyObject
*result
= NULL
;
112 if (PyArg_ParseTuple(args
, ":close")) {
113 if (self
->logfp
!= NULL
) {
123 #if Py_TPFLAGS_HAVE_ITER
124 /* This is only used if the interpreter has iterator support; the
125 * iternext handler is also used as a helper for other functions, so
126 * does not need to be included in this conditional section.
129 logreader_tp_iter(LogReaderObject
*self
)
132 return (PyObject
*) self
;
140 * The log file consists of a sequence of variable-length records.
141 * Each record is identified with a record type identifier in two
142 * bits of the first byte. The two bits are the "least significant"
145 * Low bits: Opcode: Meaning:
146 * 0x00 ENTER enter a frame
147 * 0x01 EXIT exit a frame
148 * 0x02 LINENO SET_LINENO instruction was executed
149 * 0x03 OTHER more bits are needed to deecode
151 * If the type is OTHER, the record is not packed so tightly, and the
152 * remaining bits are used to disambiguate the record type. These
153 * records are not used as frequently so compaction is not an issue.
154 * Each of the first three record types has a highly tailored
155 * structure that allows it to be packed tightly.
157 * The OTHER records have the following identifiers:
159 * First byte: Opcode: Meaning:
160 * 0x13 ADD_INFO define a key/value pair
161 * 0x23 DEFINE_FILE define an int->filename mapping
162 * 0x33 LINE_TIMES indicates if LINENO events have tdeltas
163 * 0x43 DEFINE_FUNC define a (fileno,lineno)->funcname mapping
164 * 0x53 FRAME_TIMES indicates if ENTER/EXIT events have tdeltas
168 * "Packed integers" are non-negative integer values encoded as a
169 * sequence of bytes. Each byte is encoded such that the most
170 * significant bit is set if the next byte is also part of the
171 * integer. Each byte provides bits to the least-significant end of
172 * the result; the accumulated value must be shifted up to place the
173 * new bits into the result.
175 * "Modified packed integers" are packed integers where only a portion
176 * of the first byte is used. In the rest of the specification, these
177 * are referred to as "MPI(n,name)", where "n" is the number of bits
178 * discarded from the least-signicant positions of the byte, and
179 * "name" is a name being given to those "discarded" bits, since they
180 * are a field themselves.
184 * MPI(2,type) fileno -- type is 0x00
186 * PI tdelta -- iff frame times are enabled
190 * MPI(2,type) tdelta -- type is 0x01; tdelta will be 0
191 * if frame times are disabled
195 * MPI(2,type) lineno -- type is 0x02
196 * PI tdelta -- iff LINENO includes it
200 * BYTE type -- always 0x13
201 * PI len1 -- length of first string
202 * BYTE string1[len1] -- len1 bytes of string data
203 * PI len2 -- length of second string
204 * BYTE string2[len2] -- len2 bytes of string data
206 * DEFINE_FILE records
208 * BYTE type -- always 0x23
210 * PI len -- length of filename
211 * BYTE filename[len] -- len bytes of string data
213 * DEFINE_FUNC records
215 * BYTE type -- always 0x43
218 * PI len -- length of funcname
219 * BYTE funcname[len] -- len bytes of string data
223 * This record can be used only before the start of ENTER/EXIT/LINENO
224 * records. If have_tdelta is true, LINENO records will include the
225 * tdelta field, otherwise it will be omitted. If this record is not
226 * given, LINENO records will not contain the tdelta field.
228 * BYTE type -- always 0x33
229 * BYTE have_tdelta -- 0 if LINENO does *not* have
231 * FRAME_TIMES records
233 * This record can be used only before the start of ENTER/EXIT/LINENO
234 * records. If have_tdelta is true, ENTER and EXIT records will
235 * include the tdelta field, otherwise it will be omitted. If this
236 * record is not given, ENTER and EXIT records will contain the tdelta
239 * BYTE type -- always 0x53
240 * BYTE have_tdelta -- 0 if ENTER/EXIT do *not* have
244 #define WHAT_ENTER 0x00
245 #define WHAT_EXIT 0x01
246 #define WHAT_LINENO 0x02
247 #define WHAT_OTHER 0x03 /* only used in decoding */
248 #define WHAT_ADD_INFO 0x13
249 #define WHAT_DEFINE_FILE 0x23
250 #define WHAT_LINE_TIMES 0x33
251 #define WHAT_DEFINE_FUNC 0x43
252 #define WHAT_FRAME_TIMES 0x53
256 #define ERR_EXCEPTION -2
257 #define ERR_BAD_RECTYPE -3
259 #define PISIZE (sizeof(int) + 1)
260 #define MPISIZE (PISIZE + 1)
262 /* Maximum size of "normal" events -- nothing that contains string data */
263 #define MAXEVENTSIZE (MPISIZE + PISIZE*2)
266 /* Unpack a packed integer; if "discard" is non-zero, unpack a modified
267 * packed integer with "discard" discarded bits.
270 unpack_packed_int(LogReaderObject
*self
, int *pvalue
, int discard
)
274 int index
= self
->index
;
278 if (index
>= self
->filled
)
281 accum
|= ((self
->buffer
[index
] & 0x7F) >> discard
) << bits
;
282 bits
+= (7 - discard
);
283 cont
= self
->buffer
[index
] & 0x80;
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
)
303 int oldindex
= self
->index
;
304 int err
= unpack_packed_int(self
, &len
, 0);
307 /* need at least len bytes in buffer */
308 if (len
> (self
->filled
- self
->index
)) {
309 self
->index
= oldindex
;
313 *pvalue
= PyString_FromStringAndSize((char *)self
->buffer
+ self
->index
,
315 if (*pvalue
== NULL
) {
316 self
->index
= oldindex
;
328 unpack_add_info(LogReaderObject
*self
, int skip_opcode
)
331 PyObject
*value
= NULL
;
335 if (self
->buffer
[self
->index
] != WHAT_ADD_INFO
)
336 return ERR_BAD_RECTYPE
;
339 err
= unpack_string(self
, &key
);
341 err
= unpack_string(self
, &value
);
345 PyObject
*list
= PyDict_GetItem(self
->info
, key
);
347 list
= PyList_New(0);
352 if (PyDict_SetItem(self
->info
, key
, list
)) {
357 if (PyList_Append(list
, value
))
369 logreader_refill(LogReaderObject
*self
)
375 memmove(self
->buffer
, &self
->buffer
[self
->index
],
376 self
->filled
- self
->index
);
377 self
->filled
= self
->filled
- self
->index
;
380 needed
= BUFFERSIZE
- self
->filled
;
382 res
= fread(&self
->buffer
[self
->filled
], 1, needed
, self
->logfp
);
390 PyErr_SetString(PyExc_EOFError
,
391 "end of file with incomplete profile record");
395 logreader_tp_iternext(LogReaderObject
*self
)
402 PyObject
*s1
= NULL
, *s2
= NULL
;
403 PyObject
*result
= NULL
;
405 unsigned char b0
, b1
;
408 if (self
->logfp
== NULL
) {
409 PyErr_SetString(ProfilerError
,
410 "cannot iterate over closed LogReader object");
414 if ((self
->filled
- self
->index
) < MAXEVENTSIZE
)
415 logreader_refill(self
);
418 if (self
->filled
== 0)
421 oldindex
= self
->index
;
423 /* decode the record type */
424 what
= self
->buffer
[self
->index
] & WHAT_OTHER
;
425 if (what
== WHAT_OTHER
) {
426 what
= self
->buffer
[self
->index
];
431 err
= unpack_packed_int(self
, &fileno
, 2);
433 err
= unpack_packed_int(self
, &lineno
, 0);
434 if (self
->frametimings
&& !err
)
435 err
= unpack_packed_int(self
, &tdelta
, 0);
439 err
= unpack_packed_int(self
, &tdelta
, 2);
442 err
= unpack_packed_int(self
, &lineno
, 2);
443 if (self
->linetimings
&& !err
)
444 err
= unpack_packed_int(self
, &tdelta
, 0);
447 err
= unpack_add_info(self
, 0);
449 case WHAT_DEFINE_FILE
:
450 err
= unpack_packed_int(self
, &fileno
, 0);
452 err
= unpack_string(self
, &s1
);
459 case WHAT_DEFINE_FUNC
:
460 err
= unpack_packed_int(self
, &fileno
, 0);
462 err
= unpack_packed_int(self
, &lineno
, 0);
464 err
= unpack_string(self
, &s1
);
467 case WHAT_LINE_TIMES
:
468 if (self
->index
>= self
->filled
)
471 self
->linetimings
= self
->buffer
[self
->index
] ? 1 : 0;
476 case WHAT_FRAME_TIMES
:
477 if (self
->index
>= self
->filled
)
480 self
->frametimings
= self
->buffer
[self
->index
] ? 1 : 0;
486 err
= ERR_BAD_RECTYPE
;
488 if (err
== ERR_EOF
&& oldindex
!= 0) {
489 /* It looks like we ran out of data before we had it all; this
490 * could easily happen with large packed integers or string
491 * data. Try forcing the buffer to be re-filled before failing.
494 logreader_refill(self
);
496 if (err
== ERR_BAD_RECTYPE
) {
497 PyErr_SetString(PyExc_ValueError
,
498 "unknown record type in log file");
500 else if (err
== ERR_EOF
) {
501 /* Could not avoid end-of-buffer error. */
505 result
= PyTuple_New(4);
506 PyTuple_SET_ITEM(result
, 0, PyInt_FromLong(what
));
507 PyTuple_SET_ITEM(result
, 2, PyInt_FromLong(fileno
));
509 PyTuple_SET_ITEM(result
, 1, PyInt_FromLong(tdelta
));
511 PyTuple_SET_ITEM(result
, 1, s1
);
513 PyTuple_SET_ITEM(result
, 3, PyInt_FromLong(lineno
));
515 PyTuple_SET_ITEM(result
, 3, s2
);
517 /* The only other case is err == ERR_EXCEPTION, in which case the
518 * exception is already set.
521 b0
= self
->buffer
[self
->index
];
522 b1
= self
->buffer
[self
->index
+ 1];
524 /* This is a line-number event. */
526 lineno
= ((b0
& ~1) << 7) + b1
;
530 what
= (b0
& 0x0E) >> 1;
531 tdelta
= ((b0
& 0xF0) << 4) + b1
;
532 if (what
== PyTrace_CALL
) {
533 /* we know there's a 2-byte file ID & 2-byte line number */
534 fileno
= ((self
->buffer
[self
->index
+ 2] << 8)
535 + self
->buffer
[self
->index
+ 3]);
536 lineno
= ((self
->buffer
[self
->index
+ 4] << 8)
537 + self
->buffer
[self
->index
+ 5]);
548 logreader_dealloc(LogReaderObject
*self
)
550 if (self
->logfp
!= NULL
) {
558 logreader_sq_item(LogReaderObject
*self
, int index
)
560 PyObject
*result
= logreader_tp_iternext(self
);
561 if (result
== NULL
&& !PyErr_Occurred()) {
562 PyErr_SetString(PyExc_IndexError
, "no more events in log");
568 static char next__doc__
[] =
569 "next() -> event-info\n"
570 "Return the next event record from the log file.";
573 logreader_next(LogReaderObject
*self
, PyObject
*args
)
575 PyObject
*result
= NULL
;
577 if (PyArg_ParseTuple(args
, ":next")) {
578 result
= logreader_tp_iternext(self
);
579 /* XXX return None if there's nothing left */
580 /* tp_iternext does the right thing, though */
581 if (result
== NULL
&& !PyErr_Occurred()) {
590 do_stop(ProfilerObject
*self
);
593 flush_data(ProfilerObject
*self
)
595 /* Need to dump data to the log file... */
596 size_t written
= fwrite(self
->buffer
, 1, self
->index
, self
->logfp
);
597 if (written
== (size_t)self
->index
)
600 memmove(self
->buffer
, &self
->buffer
[written
],
601 self
->index
- written
);
602 self
->index
-= written
;
604 char *s
= PyString_AsString(self
->logfilename
);
605 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, s
);
611 if (fflush(self
->logfp
)) {
612 char *s
= PyString_AsString(self
->logfilename
);
613 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, s
);
622 pack_packed_int(ProfilerObject
*self
, int value
)
624 unsigned char partial
;
627 partial
= value
& 0x7F;
631 self
->buffer
[self
->index
] = partial
;
637 /* Encode a modified packed integer, with a subfield of modsize bits
638 * containing the value "subfield". The value of subfield is not
639 * checked to ensure it actually fits in modsize bits.
642 pack_modified_packed_int(ProfilerObject
*self
, int value
,
643 int modsize
, int subfield
)
645 const int maxvalues
[] = {-1, 1, 3, 7, 15, 31, 63, 127};
647 int bits
= 7 - modsize
;
648 int partial
= value
& maxvalues
[bits
];
649 unsigned char b
= subfield
| (partial
<< modsize
);
651 if (partial
!= value
) {
653 self
->buffer
[self
->index
] = b
;
655 return pack_packed_int(self
, value
>> bits
);
657 self
->buffer
[self
->index
] = b
;
663 pack_string(ProfilerObject
*self
, const char *s
, int len
)
665 if (len
+ PISIZE
+ self
->index
>= BUFFERSIZE
) {
666 if (flush_data(self
) < 0)
669 if (pack_packed_int(self
, len
) < 0)
671 memcpy(self
->buffer
+ self
->index
, s
, len
);
677 pack_add_info(ProfilerObject
*self
, const char *s1
, const char *s2
)
679 int len1
= strlen(s1
);
680 int len2
= strlen(s2
);
682 if (len1
+ len2
+ PISIZE
*2 + 1 + self
->index
>= BUFFERSIZE
) {
683 if (flush_data(self
) < 0)
686 self
->buffer
[self
->index
] = WHAT_ADD_INFO
;
688 if (pack_string(self
, s1
, len1
) < 0)
690 return pack_string(self
, s2
, len2
);
694 pack_define_file(ProfilerObject
*self
, int fileno
, const char *filename
)
696 int len
= strlen(filename
);
698 if (len
+ PISIZE
*2 + 1 + self
->index
>= BUFFERSIZE
) {
699 if (flush_data(self
) < 0)
702 self
->buffer
[self
->index
] = WHAT_DEFINE_FILE
;
704 if (pack_packed_int(self
, fileno
) < 0)
706 return pack_string(self
, filename
, len
);
710 pack_define_func(ProfilerObject
*self
, int fileno
, int lineno
,
711 const char *funcname
)
713 int len
= strlen(funcname
);
715 if (len
+ PISIZE
*3 + 1 + self
->index
>= BUFFERSIZE
) {
716 if (flush_data(self
) < 0)
719 self
->buffer
[self
->index
] = WHAT_DEFINE_FUNC
;
721 if (pack_packed_int(self
, fileno
) < 0)
723 if (pack_packed_int(self
, lineno
) < 0)
725 return pack_string(self
, funcname
, len
);
729 pack_line_times(ProfilerObject
*self
)
731 if (2 + self
->index
>= BUFFERSIZE
) {
732 if (flush_data(self
) < 0)
735 self
->buffer
[self
->index
] = WHAT_LINE_TIMES
;
736 self
->buffer
[self
->index
+ 1] = self
->linetimings
? 1 : 0;
742 pack_frame_times(ProfilerObject
*self
)
744 if (2 + self
->index
>= BUFFERSIZE
) {
745 if (flush_data(self
) < 0)
748 self
->buffer
[self
->index
] = WHAT_FRAME_TIMES
;
749 self
->buffer
[self
->index
+ 1] = self
->frametimings
? 1 : 0;
755 pack_enter(ProfilerObject
*self
, int fileno
, int tdelta
, int lineno
)
757 if (MPISIZE
+ PISIZE
*2 + self
->index
>= BUFFERSIZE
) {
758 if (flush_data(self
) < 0)
761 pack_modified_packed_int(self
, fileno
, 2, WHAT_ENTER
);
762 pack_packed_int(self
, lineno
);
763 if (self
->frametimings
)
764 return pack_packed_int(self
, tdelta
);
770 pack_exit(ProfilerObject
*self
, int tdelta
)
772 if (MPISIZE
+ self
->index
>= BUFFERSIZE
) {
773 if (flush_data(self
) < 0)
776 if (self
->frametimings
)
777 return pack_modified_packed_int(self
, tdelta
, 2, WHAT_EXIT
);
778 self
->buffer
[self
->index
] = WHAT_EXIT
;
784 pack_lineno(ProfilerObject
*self
, int lineno
)
786 if (MPISIZE
+ self
->index
>= BUFFERSIZE
) {
787 if (flush_data(self
) < 0)
790 return pack_modified_packed_int(self
, lineno
, 2, WHAT_LINENO
);
794 pack_lineno_tdelta(ProfilerObject
*self
, int lineno
, int tdelta
)
796 if (MPISIZE
+ PISIZE
+ self
->index
>= BUFFERSIZE
) {
797 if (flush_data(self
) < 0)
800 if (pack_modified_packed_int(self
, lineno
, 2, WHAT_LINENO
) < 0)
802 return pack_packed_int(self
, tdelta
);
806 get_fileno(ProfilerObject
*self
, PyCodeObject
*fcode
)
808 /* This is only used for ENTER events. */
814 obj
= PyDict_GetItem(self
->filemap
, fcode
->co_filename
);
816 /* first sighting of this file */
821 fileno
= self
->next_fileno
;
822 obj
= Py_BuildValue("iN", fileno
, dict
);
826 if (PyDict_SetItem(self
->filemap
, fcode
->co_filename
, obj
)) {
832 if (pack_define_file(self
, fileno
,
833 PyString_AS_STRING(fcode
->co_filename
)) < 0)
837 /* already know this ID */
838 fileno
= PyInt_AS_LONG(PyTuple_GET_ITEM(obj
, 0));
839 dict
= PyTuple_GET_ITEM(obj
, 1);
841 /* make sure we save a function name for this (fileno, lineno) */
842 obj
= PyInt_FromLong(fcode
->co_firstlineno
);
844 /* We just won't have it saved; too bad. */
848 PyObject
*name
= PyDict_GetItem(dict
, obj
);
850 if (pack_define_func(self
, fileno
, fcode
->co_firstlineno
,
851 PyString_AS_STRING(fcode
->co_name
)) < 0)
853 if (PyDict_SetItem(dict
, obj
, fcode
->co_name
))
861 get_tdelta(ProfilerObject
*self
)
869 diff
= tv
- self
->prev_timeofday
;
876 if (tv
.tv_sec
== self
->prev_timeofday
.tv_sec
)
877 tdelta
= tv
.tv_usec
- self
->prev_timeofday
.tv_usec
;
879 tdelta
= ((tv
.tv_sec
- self
->prev_timeofday
.tv_sec
) * 1000000
882 self
->prev_timeofday
= tv
;
887 /* The workhorse: the profiler callback function. */
890 profiler_callback(ProfilerObject
*self
, PyFrameObject
*frame
, int what
,
896 if (self
->frametimings
)
897 tdelta
= get_tdelta(self
);
900 fileno
= get_fileno(self
, frame
->f_code
);
903 if (pack_enter(self
, fileno
, tdelta
,
904 frame
->f_code
->co_firstlineno
) < 0)
908 if (pack_exit(self
, tdelta
) < 0)
912 /* should never get here */
919 /* Alternate callback when we want PyTrace_LINE events */
922 tracer_callback(ProfilerObject
*self
, PyFrameObject
*frame
, int what
,
929 fileno
= get_fileno(self
, frame
->f_code
);
932 return pack_enter(self
, fileno
,
933 self
->frametimings
? get_tdelta(self
) : -1,
934 frame
->f_code
->co_firstlineno
);
937 return pack_exit(self
, get_tdelta(self
));
940 if (self
->linetimings
)
941 return pack_lineno_tdelta(self
, frame
->f_lineno
, get_tdelta(self
));
943 return pack_lineno(self
, frame
->f_lineno
);
946 /* ignore PyTrace_EXCEPTION */
953 /* A couple of useful helper functions. */
956 static LARGE_INTEGER frequency
= {0, 0};
959 static unsigned long timeofday_diff
= 0;
960 static unsigned long rusage_diff
= 0;
969 QueryPerformanceFrequency(&frequency
);
978 timeofday_diff
= (unsigned long)diff
;
982 if (tv1
.tv_sec
!= tv2
.tv_sec
|| tv1
.tv_usec
!= tv2
.tv_usec
) {
983 if (tv1
.tv_sec
== tv2
.tv_sec
)
984 timeofday_diff
= tv2
.tv_usec
- tv1
.tv_usec
;
986 timeofday_diff
= (1000000 - tv1
.tv_usec
) + tv2
.tv_usec
;
991 #if defined(MS_WIN32) || defined(macintosh)
995 struct rusage ru1
, ru2
;
997 getrusage(RUSAGE_SELF
, &ru1
);
999 getrusage(RUSAGE_SELF
, &ru2
);
1000 if (ru1
.ru_utime
.tv_sec
!= ru2
.ru_utime
.tv_sec
) {
1001 rusage_diff
= ((1000000 - ru1
.ru_utime
.tv_usec
)
1002 + ru2
.ru_utime
.tv_usec
);
1005 else if (ru1
.ru_utime
.tv_usec
!= ru2
.ru_utime
.tv_usec
) {
1006 rusage_diff
= ru2
.ru_utime
.tv_usec
- ru1
.ru_utime
.tv_usec
;
1009 else if (ru1
.ru_stime
.tv_sec
!= ru2
.ru_stime
.tv_sec
) {
1010 rusage_diff
= ((1000000 - ru1
.ru_stime
.tv_usec
)
1011 + ru2
.ru_stime
.tv_usec
);
1014 else if (ru1
.ru_stime
.tv_usec
!= ru2
.ru_stime
.tv_usec
) {
1015 rusage_diff
= ru2
.ru_stime
.tv_usec
- ru1
.ru_stime
.tv_usec
;
1024 do_start(ProfilerObject
*self
)
1027 GETTIMEOFDAY(&self
->prev_timeofday
);
1028 if (self
->lineevents
)
1029 PyEval_SetTrace((Py_tracefunc
) tracer_callback
, (PyObject
*)self
);
1031 PyEval_SetProfile((Py_tracefunc
) profiler_callback
, (PyObject
*)self
);
1035 do_stop(ProfilerObject
*self
)
1039 if (self
->lineevents
)
1040 PyEval_SetTrace(NULL
, NULL
);
1042 PyEval_SetProfile(NULL
, NULL
);
1044 if (self
->index
> 0) {
1045 /* Best effort to dump out any remaining data. */
1051 is_available(ProfilerObject
*self
)
1054 PyErr_SetString(ProfilerError
, "profiler already active");
1057 if (self
->logfp
== NULL
) {
1058 PyErr_SetString(ProfilerError
, "profiler already closed");
1065 /* Profiler object interface methods. */
1067 static char addinfo__doc__
[] =
1068 "addinfo(key, value)\n"
1069 "Insert an ADD_INFO record into the log.";
1072 profiler_addinfo(ProfilerObject
*self
, PyObject
*args
)
1074 PyObject
*result
= NULL
;
1077 if (PyArg_ParseTuple(args
, "ss:addinfo", &key
, &value
)) {
1078 if (self
->logfp
== NULL
)
1079 PyErr_SetString(ProfilerError
, "profiler already closed");
1081 if (pack_add_info(self
, key
, value
) == 0) {
1090 static char close__doc__
[] =
1092 "Shut down this profiler and close the log files, even if its active.";
1095 profiler_close(ProfilerObject
*self
, PyObject
*args
)
1097 PyObject
*result
= NULL
;
1099 if (PyArg_ParseTuple(args
, ":close")) {
1101 if (self
->logfp
!= NULL
) {
1102 fclose(self
->logfp
);
1111 static char runcall__doc__
[] =
1112 "runcall(callable[, args[, kw]]) -> callable()\n"
1113 "Profile a specific function call, returning the result of that call.";
1116 profiler_runcall(ProfilerObject
*self
, PyObject
*args
)
1118 PyObject
*result
= NULL
;
1119 PyObject
*callargs
= NULL
;
1120 PyObject
*callkw
= NULL
;
1123 if (PyArg_ParseTuple(args
, "O|OO:runcall",
1124 &callable
, &callargs
, &callkw
)) {
1125 if (is_available(self
)) {
1127 result
= PyEval_CallObjectWithKeywords(callable
, callargs
, callkw
);
1134 static char runcode__doc__
[] =
1135 "runcode(code, globals[, locals])\n"
1136 "Execute a code object while collecting profile data. If locals is\n"
1137 "omitted, globals is used for the locals as well.";
1140 profiler_runcode(ProfilerObject
*self
, PyObject
*args
)
1142 PyObject
*result
= NULL
;
1145 PyObject
*locals
= NULL
;
1147 if (PyArg_ParseTuple(args
, "O!O!|O:runcode",
1148 &PyCode_Type
, &code
,
1149 &PyDict_Type
, &globals
,
1151 if (is_available(self
)) {
1152 if (locals
== NULL
|| locals
== Py_None
)
1154 else if (!PyDict_Check(locals
)) {
1155 PyErr_SetString(PyExc_TypeError
,
1156 "locals must be a dictionary or None");
1160 result
= PyEval_EvalCode(code
, globals
, locals
);
1163 if (!PyErr_Occurred()) {
1173 static char start__doc__
[] =
1175 "Install this profiler for the current thread.";
1178 profiler_start(ProfilerObject
*self
, PyObject
*args
)
1180 PyObject
*result
= NULL
;
1182 if (PyArg_ParseTuple(args
, ":start")) {
1183 if (is_available(self
)) {
1192 static char stop__doc__
[] =
1194 "Remove this profiler from the current thread.";
1197 profiler_stop(ProfilerObject
*self
, PyObject
*args
)
1199 PyObject
*result
= NULL
;
1201 if (PyArg_ParseTuple(args
, ":stop")) {
1203 PyErr_SetString(ProfilerError
, "profiler not active");
1214 /* Python API support. */
1217 profiler_dealloc(ProfilerObject
*self
)
1220 if (self
->logfp
!= NULL
)
1221 fclose(self
->logfp
);
1222 Py_XDECREF(self
->filemap
);
1223 Py_XDECREF(self
->logfilename
);
1224 PyObject_Del((PyObject
*)self
);
1227 /* Always use METH_VARARGS even though some of these could be METH_NOARGS;
1228 * this allows us to maintain compatibility with Python versions < 2.2
1229 * more easily, requiring only the changes to the dispatcher to be made.
1231 static PyMethodDef profiler_methods
[] = {
1232 {"addinfo", (PyCFunction
)profiler_addinfo
, METH_VARARGS
, addinfo__doc__
},
1233 {"close", (PyCFunction
)profiler_close
, METH_VARARGS
, close__doc__
},
1234 {"runcall", (PyCFunction
)profiler_runcall
, METH_VARARGS
, runcall__doc__
},
1235 {"runcode", (PyCFunction
)profiler_runcode
, METH_VARARGS
, runcode__doc__
},
1236 {"start", (PyCFunction
)profiler_start
, METH_VARARGS
, start__doc__
},
1237 {"stop", (PyCFunction
)profiler_stop
, METH_VARARGS
, stop__doc__
},
1241 /* Use a table even though there's only one "simple" member; this allows
1242 * __members__ and therefore dir() to work.
1244 static struct memberlist profiler_members
[] = {
1245 {"closed", T_INT
, -1, READONLY
},
1246 {"frametimings", T_LONG
, offsetof(ProfilerObject
, linetimings
), READONLY
},
1247 {"lineevents", T_LONG
, offsetof(ProfilerObject
, lineevents
), READONLY
},
1248 {"linetimings", T_LONG
, offsetof(ProfilerObject
, linetimings
), READONLY
},
1253 profiler_getattr(ProfilerObject
*self
, char *name
)
1256 if (strcmp(name
, "closed") == 0) {
1257 result
= (self
->logfp
== NULL
) ? Py_True
: Py_False
;
1261 result
= PyMember_Get((char *)self
, profiler_members
, name
);
1262 if (result
== NULL
) {
1264 result
= Py_FindMethod(profiler_methods
, (PyObject
*)self
, name
);
1271 static char profiler_object__doc__
[] =
1272 "High-performance profiler object.\n"
1276 "close(): Stop the profiler and close the log files.\n"
1277 "runcall(): Run a single function call with profiling enabled.\n"
1278 "runcode(): Execute a code object with profiling enabled.\n"
1279 "start(): Install the profiler and return.\n"
1280 "stop(): Remove the profiler.\n"
1282 "Attributes (read-only):\n"
1284 "closed: True if the profiler has already been closed.\n"
1285 "frametimings: True if ENTER/EXIT events collect timing information.\n"
1286 "lineevents: True if SET_LINENO events are reported to the profiler.\n"
1287 "linetimings: True if SET_LINENO events collect timing information.";
1289 static PyTypeObject ProfilerType
= {
1290 PyObject_HEAD_INIT(NULL
)
1292 "_hotshot.ProfilerType", /* tp_name */
1293 (int) sizeof(ProfilerObject
), /* tp_basicsize */
1294 0, /* tp_itemsize */
1295 (destructor
)profiler_dealloc
, /* tp_dealloc */
1297 (getattrfunc
)profiler_getattr
, /* tp_getattr */
1301 0, /* tp_as_number */
1302 0, /* tp_as_sequence */
1303 0, /* tp_as_mapping */
1307 0, /* tp_getattro */
1308 0, /* tp_setattro */
1309 0, /* tp_as_buffer */
1310 Py_TPFLAGS_DEFAULT
, /* tp_flags */
1311 profiler_object__doc__
, /* tp_doc */
1315 static PyMethodDef logreader_methods
[] = {
1316 {"close", (PyCFunction
)logreader_close
, METH_VARARGS
,
1317 logreader_close__doc__
},
1318 {"next", (PyCFunction
)logreader_next
, METH_VARARGS
,
1324 logreader_getattr(LogReaderObject
*self
, char *name
)
1326 if (strcmp(name
, "info") == 0) {
1327 Py_INCREF(self
->info
);
1330 return Py_FindMethod(logreader_methods
, (PyObject
*)self
, name
);
1334 static char logreader__doc__
[] = "\
1335 logreader(filename) --> log-iterator\n\
1336 Create a log-reader for the timing information file.";
1338 static PySequenceMethods logreader_as_sequence
= {
1342 (intargfunc
)logreader_sq_item
, /* sq_item */
1344 0, /* sq_ass_item */
1345 0, /* sq_ass_slice */
1346 0, /* sq_contains */
1347 0, /* sq_inplace_concat */
1348 0, /* sq_inplace_repeat */
1351 static PyTypeObject LogReaderType
= {
1352 PyObject_HEAD_INIT(NULL
)
1354 "_hotshot.LogReaderType", /* tp_name */
1355 (int) sizeof(LogReaderObject
), /* tp_basicsize */
1356 0, /* tp_itemsize */
1357 (destructor
)logreader_dealloc
, /* tp_dealloc */
1359 (getattrfunc
)logreader_getattr
, /* tp_getattr */
1363 0, /* tp_as_number */
1364 &logreader_as_sequence
, /* tp_as_sequence */
1365 0, /* tp_as_mapping */
1369 0, /* tp_getattro */
1370 0, /* tp_setattro */
1371 0, /* tp_as_buffer */
1372 Py_TPFLAGS_DEFAULT
, /* tp_flags */
1373 logreader__doc__
, /* tp_doc */
1374 #if Py_TPFLAGS_HAVE_ITER
1375 0, /* tp_traverse */
1377 0, /* tp_richcompare */
1378 0, /* tp_weaklistoffset */
1379 (getiterfunc
)logreader_tp_iter
, /* tp_iter */
1380 (iternextfunc
)logreader_tp_iternext
,/* tp_iternext */
1385 hotshot_logreader(PyObject
*unused
, PyObject
*args
)
1387 LogReaderObject
*self
= NULL
;
1390 if (PyArg_ParseTuple(args
, "s:logreader", &filename
)) {
1391 self
= PyObject_New(LogReaderObject
, &LogReaderType
);
1395 self
->frametimings
= 1;
1396 self
->linetimings
= 0;
1398 self
->logfp
= fopen(filename
, "rb");
1399 if (self
->logfp
== NULL
) {
1400 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, filename
);
1405 self
->info
= PyDict_New();
1406 if (self
->info
== NULL
) {
1410 /* Aggressively attempt to load all preliminary ADD_INFO
1411 * records from the log so the info records are available
1412 * from a fresh logreader object.
1414 logreader_refill(self
);
1415 while (self
->filled
> self
->index
1416 && self
->buffer
[self
->index
] == WHAT_ADD_INFO
) {
1417 int err
= unpack_add_info(self
, 1);
1422 PyErr_SetString(PyExc_RuntimeError
,
1423 "unexpected error");
1426 /* Refill agressively so we can avoid EOF during
1427 * initialization unless there's a real EOF condition
1428 * (the tp_iternext handler loops attempts to refill
1431 logreader_refill(self
);
1436 return (PyObject
*) self
;
1440 /* Return a Python string that represents the version number without the
1441 * extra cruft added by revision control, even if the right options were
1442 * given to the "cvs export" command to make it not include the extra
1446 get_version_string(void)
1448 static char *rcsid
= "$Revision$";
1453 while (*rev
&& !isdigit(*rev
))
1455 while (rev
[i
] != ' ' && rev
[i
] != '\0')
1457 buffer
= malloc(i
+ 1);
1458 if (buffer
!= NULL
) {
1459 memmove(buffer
, rev
, i
);
1465 /* Write out a RFC 822-style header with various useful bits of
1466 * information to make the output easier to manage.
1469 write_header(ProfilerObject
*self
)
1472 char cwdbuffer
[PATH_MAX
];
1476 buffer
= get_version_string();
1477 if (buffer
== NULL
) {
1481 pack_add_info(self
, "hotshot-version", buffer
);
1482 pack_add_info(self
, "requested-frame-timings",
1483 (self
->frametimings
? "yes" : "no"));
1484 pack_add_info(self
, "requested-line-events",
1485 (self
->lineevents
? "yes" : "no"));
1486 pack_add_info(self
, "requested-line-timings",
1487 (self
->linetimings
? "yes" : "no"));
1488 pack_add_info(self
, "platform", Py_GetPlatform());
1489 pack_add_info(self
, "executable", Py_GetProgramFullPath());
1491 buffer
= (char *) Py_GetVersion();
1495 pack_add_info(self
, "executable-version", buffer
);
1498 PyOS_snprintf(cwdbuffer
, sizeof(cwdbuffer
), "%I64d", frequency
.QuadPart
);
1499 pack_add_info(self
, "reported-performance-frequency", cwdbuffer
);
1501 PyOS_snprintf(cwdbuffer
, sizeof(cwdbuffer
), "%lu", rusage_diff
);
1502 pack_add_info(self
, "observed-interval-getrusage", cwdbuffer
);
1503 PyOS_snprintf(cwdbuffer
, sizeof(cwdbuffer
), "%lu", timeofday_diff
);
1504 pack_add_info(self
, "observed-interval-gettimeofday", cwdbuffer
);
1507 pack_add_info(self
, "current-directory",
1508 getcwd(cwdbuffer
, sizeof cwdbuffer
));
1510 temp
= PySys_GetObject("path");
1511 len
= PyList_GET_SIZE(temp
);
1512 for (i
= 0; i
< len
; ++i
) {
1513 PyObject
*item
= PyList_GET_ITEM(temp
, i
);
1514 buffer
= PyString_AsString(item
);
1517 pack_add_info(self
, "sys-path-entry", buffer
);
1519 pack_frame_times(self
);
1520 pack_line_times(self
);
1525 static char profiler__doc__
[] = "\
1526 profiler(logfilename[, lineevents[, linetimes]]) -> profiler\n\
1527 Create a new profiler object.";
1530 hotshot_profiler(PyObject
*unused
, PyObject
*args
)
1533 ProfilerObject
*self
= NULL
;
1535 int linetimings
= 1;
1537 if (PyArg_ParseTuple(args
, "s|ii:profiler", &logfilename
,
1538 &lineevents
, &linetimings
)) {
1539 self
= PyObject_New(ProfilerObject
, &ProfilerType
);
1542 self
->frametimings
= 1;
1543 self
->lineevents
= lineevents
? 1 : 0;
1544 self
->linetimings
= (lineevents
&& linetimings
) ? 1 : 0;
1547 self
->next_fileno
= 0;
1549 self
->logfilename
= PyTuple_GET_ITEM(args
, 0);
1550 Py_INCREF(self
->logfilename
);
1551 self
->filemap
= PyDict_New();
1552 if (self
->filemap
== NULL
) {
1556 self
->logfp
= fopen(logfilename
, "wb");
1557 if (self
->logfp
== NULL
) {
1559 PyErr_SetFromErrnoWithFilename(PyExc_IOError
, logfilename
);
1562 if (timeofday_diff
== 0) {
1563 /* Run this several times since sometimes the first
1564 * doesn't give the lowest values, and we're really trying
1565 * to determine the lowest.
1571 if (write_header(self
))
1572 /* some error occurred, exception has been set */
1575 return (PyObject
*) self
;
1578 static char coverage__doc__
[] = "\
1579 coverage(logfilename) -> profiler\n\
1580 Returns a profiler that doesn't collect any timing information, which is\n\
1581 useful in building a coverage analysis tool.";
1584 hotshot_coverage(PyObject
*unused
, PyObject
*args
)
1587 PyObject
*result
= NULL
;
1589 if (PyArg_ParseTuple(args
, "s:coverage", &logfilename
)) {
1590 result
= hotshot_profiler(unused
, args
);
1591 if (result
!= NULL
) {
1592 ProfilerObject
*self
= (ProfilerObject
*) result
;
1593 self
->frametimings
= 0;
1594 self
->linetimings
= 0;
1595 self
->lineevents
= 1;
1601 static char resolution__doc__
[] =
1603 "resolution() -> (performance-counter-ticks, update-frequency)\n"
1604 "Return the resolution of the timer provided by the QueryPerformanceCounter()\n"
1605 "function. The first value is the smallest observed change, and the second\n"
1606 "is the result of QueryPerformanceFrequency().";
1608 "resolution() -> (gettimeofday-usecs, getrusage-usecs)\n"
1609 "Return the resolution of the timers provided by the gettimeofday() and\n"
1610 "getrusage() system calls, or -1 if the call is not supported.";
1614 hotshot_resolution(PyObject
*unused
, PyObject
*args
)
1616 PyObject
*result
= NULL
;
1618 if (PyArg_ParseTuple(args
, ":resolution")) {
1619 if (timeofday_diff
== 0) {
1625 result
= Py_BuildValue("ii", timeofday_diff
, frequency
.LowPart
);
1627 result
= Py_BuildValue("ii", timeofday_diff
, rusage_diff
);
1634 static PyMethodDef functions
[] = {
1635 {"coverage", hotshot_coverage
, METH_VARARGS
, coverage__doc__
},
1636 {"profiler", hotshot_profiler
, METH_VARARGS
, profiler__doc__
},
1637 {"logreader", hotshot_logreader
, METH_VARARGS
, logreader__doc__
},
1638 {"resolution", hotshot_resolution
, METH_VARARGS
, resolution__doc__
},
1648 LogReaderType
.ob_type
= &PyType_Type
;
1649 ProfilerType
.ob_type
= &PyType_Type
;
1650 module
= Py_InitModule("_hotshot", functions
);
1651 if (module
!= NULL
) {
1652 char *s
= get_version_string();
1654 PyModule_AddStringConstant(module
, "__version__", s
);
1656 Py_INCREF(&LogReaderType
);
1657 PyModule_AddObject(module
, "LogReaderType",
1658 (PyObject
*)&LogReaderType
);
1659 Py_INCREF(&ProfilerType
);
1660 PyModule_AddObject(module
, "ProfilerType",
1661 (PyObject
*)&ProfilerType
);
1663 if (ProfilerError
== NULL
)
1664 ProfilerError
= PyErr_NewException("hotshot.ProfilerError",
1666 if (ProfilerError
!= NULL
) {
1667 Py_INCREF(ProfilerError
);
1668 PyModule_AddObject(module
, "ProfilerError", ProfilerError
);
1670 PyModule_AddIntConstant(module
, "WHAT_ENTER", WHAT_ENTER
);
1671 PyModule_AddIntConstant(module
, "WHAT_EXIT", WHAT_EXIT
);
1672 PyModule_AddIntConstant(module
, "WHAT_LINENO", WHAT_LINENO
);
1673 PyModule_AddIntConstant(module
, "WHAT_OTHER", WHAT_OTHER
);
1674 PyModule_AddIntConstant(module
, "WHAT_ADD_INFO", WHAT_ADD_INFO
);
1675 PyModule_AddIntConstant(module
, "WHAT_DEFINE_FILE", WHAT_DEFINE_FILE
);
1676 PyModule_AddIntConstant(module
, "WHAT_DEFINE_FUNC", WHAT_DEFINE_FUNC
);
1677 PyModule_AddIntConstant(module
, "WHAT_LINE_TIMES", WHAT_LINE_TIMES
);