/Modules/_lsprof.c

http://unladen-swallow.googlecode.com/ · C · 905 lines · 773 code · 85 blank · 47 comment · 119 complexity · 7b4fab24e75dfcf80aa92a450d9cb354 MD5 · raw file

  1. #include "Python.h"
  2. #include "compile.h"
  3. #include "frameobject.h"
  4. #include "structseq.h"
  5. #include "rotatingtree.h"
  6. #if !defined(HAVE_LONG_LONG)
  7. #error "This module requires long longs!"
  8. #endif
  9. /*** Selection of a high-precision timer ***/
  10. #ifdef MS_WINDOWS
  11. #include <windows.h>
  12. static PY_LONG_LONG
  13. hpTimer(void)
  14. {
  15. LARGE_INTEGER li;
  16. QueryPerformanceCounter(&li);
  17. return li.QuadPart;
  18. }
  19. static double
  20. hpTimerUnit(void)
  21. {
  22. LARGE_INTEGER li;
  23. if (QueryPerformanceFrequency(&li))
  24. return 1.0 / li.QuadPart;
  25. else
  26. return 0.000001; /* unlikely */
  27. }
  28. #else /* !MS_WINDOWS */
  29. #ifndef HAVE_GETTIMEOFDAY
  30. #error "This module requires gettimeofday() on non-Windows platforms!"
  31. #endif
  32. #if (defined(PYOS_OS2) && defined(PYCC_GCC))
  33. #include <sys/time.h>
  34. #else
  35. #include <sys/resource.h>
  36. #include <sys/times.h>
  37. #endif
  38. static PY_LONG_LONG
  39. hpTimer(void)
  40. {
  41. struct timeval tv;
  42. PY_LONG_LONG ret;
  43. #ifdef GETTIMEOFDAY_NO_TZ
  44. gettimeofday(&tv);
  45. #else
  46. gettimeofday(&tv, (struct timezone *)NULL);
  47. #endif
  48. ret = tv.tv_sec;
  49. ret = ret * 1000000 + tv.tv_usec;
  50. return ret;
  51. }
  52. static double
  53. hpTimerUnit(void)
  54. {
  55. return 0.000001;
  56. }
  57. #endif /* MS_WINDOWS */
  58. /************************************************************/
  59. /* Written by Brett Rosen and Ted Czotter */
  60. struct _ProfilerEntry;
  61. /* represents a function called from another function */
  62. typedef struct _ProfilerSubEntry {
  63. rotating_node_t header;
  64. PY_LONG_LONG tt;
  65. PY_LONG_LONG it;
  66. long callcount;
  67. long recursivecallcount;
  68. long recursionLevel;
  69. } ProfilerSubEntry;
  70. /* represents a function or user defined block */
  71. typedef struct _ProfilerEntry {
  72. rotating_node_t header;
  73. PyObject *userObj; /* PyCodeObject, or a descriptive str for builtins */
  74. PY_LONG_LONG tt; /* total time in this entry */
  75. PY_LONG_LONG it; /* inline time in this entry (not in subcalls) */
  76. long callcount; /* how many times this was called */
  77. long recursivecallcount; /* how many times called recursively */
  78. long recursionLevel;
  79. rotating_node_t *calls;
  80. } ProfilerEntry;
  81. typedef struct _ProfilerContext {
  82. PY_LONG_LONG t0;
  83. PY_LONG_LONG subt;
  84. struct _ProfilerContext *previous;
  85. ProfilerEntry *ctxEntry;
  86. } ProfilerContext;
  87. typedef struct {
  88. PyObject_HEAD
  89. rotating_node_t *profilerEntries;
  90. ProfilerContext *currentProfilerContext;
  91. ProfilerContext *freelistProfilerContext;
  92. int flags;
  93. PyObject *externalTimer;
  94. double externalTimerUnit;
  95. } ProfilerObject;
  96. #define POF_ENABLED 0x001
  97. #define POF_SUBCALLS 0x002
  98. #define POF_BUILTINS 0x004
  99. #define POF_NOMEMORY 0x100
  100. staticforward PyTypeObject PyProfiler_Type;
  101. #define PyProfiler_Check(op) PyObject_TypeCheck(op, &PyProfiler_Type)
  102. #define PyProfiler_CheckExact(op) (Py_TYPE(op) == &PyProfiler_Type)
  103. /*** External Timers ***/
  104. #define DOUBLE_TIMER_PRECISION 4294967296.0
  105. static PyObject *empty_tuple;
  106. static PY_LONG_LONG CallExternalTimer(ProfilerObject *pObj)
  107. {
  108. PY_LONG_LONG result;
  109. PyObject *o = PyObject_Call(pObj->externalTimer, empty_tuple, NULL);
  110. if (o == NULL) {
  111. PyErr_WriteUnraisable(pObj->externalTimer);
  112. return 0;
  113. }
  114. if (pObj->externalTimerUnit > 0.0) {
  115. /* interpret the result as an integer that will be scaled
  116. in profiler_getstats() */
  117. result = PyLong_AsLongLong(o);
  118. }
  119. else {
  120. /* interpret the result as a double measured in seconds.
  121. As the profiler works with PY_LONG_LONG internally
  122. we convert it to a large integer */
  123. double val = PyFloat_AsDouble(o);
  124. /* error handling delayed to the code below */
  125. result = (PY_LONG_LONG) (val * DOUBLE_TIMER_PRECISION);
  126. }
  127. Py_DECREF(o);
  128. if (PyErr_Occurred()) {
  129. PyErr_WriteUnraisable(pObj->externalTimer);
  130. return 0;
  131. }
  132. return result;
  133. }
  134. #define CALL_TIMER(pObj) ((pObj)->externalTimer ? \
  135. CallExternalTimer(pObj) : \
  136. hpTimer())
  137. /*** ProfilerObject ***/
  138. static PyObject *
  139. normalizeUserObj(PyObject *obj)
  140. {
  141. /* Replace built-in function objects with a descriptive string
  142. because of built-in methods -- keeping a reference to
  143. __self__ is probably not a good idea. */
  144. PyCFunctionObject *fn = (PyCFunctionObject *)obj;
  145. if (PyCFunction_Check(obj) && fn->m_self == NULL) {
  146. /* built-in function: look up the module name */
  147. PyObject *mod = fn->m_module;
  148. char *modname;
  149. if (mod && PyString_Check(mod)) {
  150. modname = PyString_AS_STRING(mod);
  151. }
  152. else if (mod && PyModule_Check(mod)) {
  153. modname = PyModule_GetName(mod);
  154. if (modname == NULL) {
  155. PyErr_Clear();
  156. modname = "__builtin__";
  157. }
  158. }
  159. else {
  160. modname = "__builtin__";
  161. }
  162. if (strcmp(modname, "__builtin__") != 0)
  163. return PyString_FromFormat("<%s.%s>",
  164. modname,
  165. fn->m_ml->ml_name);
  166. else
  167. return PyString_FromFormat("<%s>",
  168. fn->m_ml->ml_name);
  169. }
  170. else if (PyCFunction_Check(obj) || PyMethodDescr_Check(obj)) {
  171. /* built-in method: try to return
  172. repr(getattr(type(__self__), __name__))
  173. */
  174. PyTypeObject *type;
  175. const char *name;
  176. PyObject *name_obj;
  177. if (PyCFunction_Check(obj)) {
  178. type = Py_TYPE(fn->m_self);
  179. name = fn->m_ml->ml_name;
  180. }
  181. else {
  182. PyMethodDescrObject *descr = (PyMethodDescrObject *)obj;
  183. type = descr->d_type;
  184. name = descr->d_method->ml_name;
  185. }
  186. name_obj = PyString_FromString(name);
  187. if (name_obj != NULL) {
  188. PyObject *mo = _PyType_Lookup(type, name_obj);
  189. Py_XINCREF(mo);
  190. Py_DECREF(name_obj);
  191. if (mo != NULL) {
  192. PyObject *res = PyObject_Repr(mo);
  193. Py_DECREF(mo);
  194. if (res != NULL)
  195. return res;
  196. }
  197. }
  198. PyErr_Clear();
  199. return PyString_FromFormat("<built-in method %s>", name);
  200. }
  201. else {
  202. Py_INCREF(obj);
  203. return obj;
  204. }
  205. }
  206. static ProfilerEntry*
  207. newProfilerEntry(ProfilerObject *pObj, void *key, PyObject *userObj)
  208. {
  209. ProfilerEntry *self;
  210. self = (ProfilerEntry*) malloc(sizeof(ProfilerEntry));
  211. if (self == NULL) {
  212. pObj->flags |= POF_NOMEMORY;
  213. return NULL;
  214. }
  215. userObj = normalizeUserObj(userObj);
  216. if (userObj == NULL) {
  217. PyErr_Clear();
  218. free(self);
  219. pObj->flags |= POF_NOMEMORY;
  220. return NULL;
  221. }
  222. self->header.key = key;
  223. self->userObj = userObj;
  224. self->tt = 0;
  225. self->it = 0;
  226. self->callcount = 0;
  227. self->recursivecallcount = 0;
  228. self->recursionLevel = 0;
  229. self->calls = EMPTY_ROTATING_TREE;
  230. RotatingTree_Add(&pObj->profilerEntries, &self->header);
  231. return self;
  232. }
  233. static ProfilerEntry*
  234. getEntry(ProfilerObject *pObj, void *key)
  235. {
  236. return (ProfilerEntry*) RotatingTree_Get(&pObj->profilerEntries, key);
  237. }
  238. static ProfilerSubEntry *
  239. getSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
  240. {
  241. return (ProfilerSubEntry*) RotatingTree_Get(&caller->calls,
  242. (void *)entry);
  243. }
  244. static ProfilerSubEntry *
  245. newSubEntry(ProfilerObject *pObj, ProfilerEntry *caller, ProfilerEntry* entry)
  246. {
  247. ProfilerSubEntry *self;
  248. self = (ProfilerSubEntry*) malloc(sizeof(ProfilerSubEntry));
  249. if (self == NULL) {
  250. pObj->flags |= POF_NOMEMORY;
  251. return NULL;
  252. }
  253. self->header.key = (void *)entry;
  254. self->tt = 0;
  255. self->it = 0;
  256. self->callcount = 0;
  257. self->recursivecallcount = 0;
  258. self->recursionLevel = 0;
  259. RotatingTree_Add(&caller->calls, &self->header);
  260. return self;
  261. }
  262. static int freeSubEntry(rotating_node_t *header, void *arg)
  263. {
  264. ProfilerSubEntry *subentry = (ProfilerSubEntry*) header;
  265. free(subentry);
  266. return 0;
  267. }
  268. static int freeEntry(rotating_node_t *header, void *arg)
  269. {
  270. ProfilerEntry *entry = (ProfilerEntry*) header;
  271. RotatingTree_Enum(entry->calls, freeSubEntry, NULL);
  272. Py_DECREF(entry->userObj);
  273. free(entry);
  274. return 0;
  275. }
  276. static void clearEntries(ProfilerObject *pObj)
  277. {
  278. RotatingTree_Enum(pObj->profilerEntries, freeEntry, NULL);
  279. pObj->profilerEntries = EMPTY_ROTATING_TREE;
  280. /* release the memory hold by the free list of ProfilerContexts */
  281. while (pObj->freelistProfilerContext) {
  282. ProfilerContext *c = pObj->freelistProfilerContext;
  283. pObj->freelistProfilerContext = c->previous;
  284. free(c);
  285. }
  286. }
  287. static void
  288. initContext(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
  289. {
  290. self->ctxEntry = entry;
  291. self->subt = 0;
  292. self->previous = pObj->currentProfilerContext;
  293. pObj->currentProfilerContext = self;
  294. ++entry->recursionLevel;
  295. if ((pObj->flags & POF_SUBCALLS) && self->previous) {
  296. /* find or create an entry for me in my caller's entry */
  297. ProfilerEntry *caller = self->previous->ctxEntry;
  298. ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
  299. if (subentry == NULL)
  300. subentry = newSubEntry(pObj, caller, entry);
  301. if (subentry)
  302. ++subentry->recursionLevel;
  303. }
  304. self->t0 = CALL_TIMER(pObj);
  305. }
  306. static void
  307. Stop(ProfilerObject *pObj, ProfilerContext *self, ProfilerEntry *entry)
  308. {
  309. PY_LONG_LONG tt = CALL_TIMER(pObj) - self->t0;
  310. PY_LONG_LONG it = tt - self->subt;
  311. if (self->previous)
  312. self->previous->subt += tt;
  313. pObj->currentProfilerContext = self->previous;
  314. if (--entry->recursionLevel == 0)
  315. entry->tt += tt;
  316. else
  317. ++entry->recursivecallcount;
  318. entry->it += it;
  319. entry->callcount++;
  320. if ((pObj->flags & POF_SUBCALLS) && self->previous) {
  321. /* find or create an entry for me in my caller's entry */
  322. ProfilerEntry *caller = self->previous->ctxEntry;
  323. ProfilerSubEntry *subentry = getSubEntry(pObj, caller, entry);
  324. if (subentry) {
  325. if (--subentry->recursionLevel == 0)
  326. subentry->tt += tt;
  327. else
  328. ++subentry->recursivecallcount;
  329. subentry->it += it;
  330. ++subentry->callcount;
  331. }
  332. }
  333. }
  334. static void
  335. ptrace_enter_call(PyObject *self, void *key, PyObject *userObj)
  336. {
  337. /* entering a call to the function identified by 'key'
  338. (which can be a PyCodeObject or a PyMethodDef pointer) */
  339. ProfilerObject *pObj = (ProfilerObject*)self;
  340. ProfilerEntry *profEntry;
  341. ProfilerContext *pContext;
  342. /* In the case of entering a generator expression frame via a
  343. * throw (gen_send_ex(.., 1)), we may already have an
  344. * Exception set here. We must not mess around with this
  345. * exception, and some of the code under here assumes that
  346. * PyErr_* is its own to mess around with, so we have to
  347. * save and restore any current exception. */
  348. PyObject *last_type, *last_value, *last_tb;
  349. PyErr_Fetch(&last_type, &last_value, &last_tb);
  350. profEntry = getEntry(pObj, key);
  351. if (profEntry == NULL) {
  352. profEntry = newProfilerEntry(pObj, key, userObj);
  353. if (profEntry == NULL)
  354. goto restorePyerr;
  355. }
  356. /* grab a ProfilerContext out of the free list */
  357. pContext = pObj->freelistProfilerContext;
  358. if (pContext) {
  359. pObj->freelistProfilerContext = pContext->previous;
  360. }
  361. else {
  362. /* free list exhausted, allocate a new one */
  363. pContext = (ProfilerContext*)
  364. malloc(sizeof(ProfilerContext));
  365. if (pContext == NULL) {
  366. pObj->flags |= POF_NOMEMORY;
  367. goto restorePyerr;
  368. }
  369. }
  370. initContext(pObj, pContext, profEntry);
  371. restorePyerr:
  372. PyErr_Restore(last_type, last_value, last_tb);
  373. }
  374. static void
  375. ptrace_leave_call(PyObject *self, void *key)
  376. {
  377. /* leaving a call to the function identified by 'key' */
  378. ProfilerObject *pObj = (ProfilerObject*)self;
  379. ProfilerEntry *profEntry;
  380. ProfilerContext *pContext;
  381. pContext = pObj->currentProfilerContext;
  382. if (pContext == NULL)
  383. return;
  384. profEntry = getEntry(pObj, key);
  385. if (profEntry) {
  386. Stop(pObj, pContext, profEntry);
  387. }
  388. else {
  389. pObj->currentProfilerContext = pContext->previous;
  390. }
  391. /* put pContext into the free list */
  392. pContext->previous = pObj->freelistProfilerContext;
  393. pObj->freelistProfilerContext = pContext;
  394. }
  395. static int
  396. profiler_callback(PyObject *self, PyFrameObject *frame, int what,
  397. PyObject *arg)
  398. {
  399. switch (what) {
  400. /* the 'frame' of a called function is about to start its execution */
  401. case PyTrace_CALL:
  402. ptrace_enter_call(self, (void *)frame->f_code,
  403. (PyObject *)frame->f_code);
  404. break;
  405. /* the 'frame' of a called function is about to finish
  406. (either normally or with an exception) */
  407. case PyTrace_RETURN:
  408. ptrace_leave_call(self, (void *)frame->f_code);
  409. break;
  410. /* case PyTrace_EXCEPTION:
  411. If the exception results in the function exiting, a
  412. PyTrace_RETURN event will be generated, so we don't need to
  413. handle it. */
  414. #ifdef PyTrace_C_CALL /* not defined in Python <= 2.3 */
  415. /* the Python function 'frame' is issuing a call to the built-in
  416. function 'arg' */
  417. case PyTrace_C_CALL:
  418. if (((ProfilerObject *)self)->flags & POF_BUILTINS) {
  419. PyMethodDef *ml = NULL;
  420. if (PyCFunction_Check(arg)) {
  421. ml = ((PyCFunctionObject *)arg)->m_ml;
  422. }
  423. else if (PyMethodDescr_Check(arg)) {
  424. ml = ((PyMethodDescrObject*)arg)->d_method;
  425. }
  426. ptrace_enter_call(self, ml, arg);
  427. }
  428. break;
  429. /* the call to the built-in function 'arg' is returning into its
  430. caller 'frame' */
  431. case PyTrace_C_RETURN: /* ...normally */
  432. case PyTrace_C_EXCEPTION: /* ...with an exception set */
  433. if (((ProfilerObject *)self)->flags & POF_BUILTINS) {
  434. PyMethodDef *ml = NULL;
  435. if (PyCFunction_Check(arg)) {
  436. ml = ((PyCFunctionObject *)arg)->m_ml;
  437. }
  438. else if (PyMethodDescr_Check(arg)) {
  439. ml = ((PyMethodDescrObject*)arg)->d_method;
  440. }
  441. ptrace_leave_call(self, ml);
  442. }
  443. break;
  444. #endif
  445. default:
  446. break;
  447. }
  448. return 0;
  449. }
  450. static int
  451. pending_exception(ProfilerObject *pObj)
  452. {
  453. if (pObj->flags & POF_NOMEMORY) {
  454. pObj->flags -= POF_NOMEMORY;
  455. PyErr_SetString(PyExc_MemoryError,
  456. "memory was exhausted while profiling");
  457. return -1;
  458. }
  459. return 0;
  460. }
  461. /************************************************************/
  462. static PyStructSequence_Field profiler_entry_fields[] = {
  463. {"code", "code object or built-in function name"},
  464. {"callcount", "how many times this was called"},
  465. {"reccallcount", "how many times called recursively"},
  466. {"totaltime", "total time in this entry"},
  467. {"inlinetime", "inline time in this entry (not in subcalls)"},
  468. {"calls", "details of the calls"},
  469. {0}
  470. };
  471. static PyStructSequence_Field profiler_subentry_fields[] = {
  472. {"code", "called code object or built-in function name"},
  473. {"callcount", "how many times this is called"},
  474. {"reccallcount", "how many times this is called recursively"},
  475. {"totaltime", "total time spent in this call"},
  476. {"inlinetime", "inline time (not in further subcalls)"},
  477. {0}
  478. };
  479. static PyStructSequence_Desc profiler_entry_desc = {
  480. "_lsprof.profiler_entry", /* name */
  481. NULL, /* doc */
  482. profiler_entry_fields,
  483. 6
  484. };
  485. static PyStructSequence_Desc profiler_subentry_desc = {
  486. "_lsprof.profiler_subentry", /* name */
  487. NULL, /* doc */
  488. profiler_subentry_fields,
  489. 5
  490. };
  491. static int initialized;
  492. static PyTypeObject StatsEntryType;
  493. static PyTypeObject StatsSubEntryType;
  494. typedef struct {
  495. PyObject *list;
  496. PyObject *sublist;
  497. double factor;
  498. } statscollector_t;
  499. static int statsForSubEntry(rotating_node_t *node, void *arg)
  500. {
  501. ProfilerSubEntry *sentry = (ProfilerSubEntry*) node;
  502. statscollector_t *collect = (statscollector_t*) arg;
  503. ProfilerEntry *entry = (ProfilerEntry*) sentry->header.key;
  504. int err;
  505. PyObject *sinfo;
  506. sinfo = PyObject_CallFunction((PyObject*) &StatsSubEntryType,
  507. "((Olldd))",
  508. entry->userObj,
  509. sentry->callcount,
  510. sentry->recursivecallcount,
  511. collect->factor * sentry->tt,
  512. collect->factor * sentry->it);
  513. if (sinfo == NULL)
  514. return -1;
  515. err = PyList_Append(collect->sublist, sinfo);
  516. Py_DECREF(sinfo);
  517. return err;
  518. }
  519. static int statsForEntry(rotating_node_t *node, void *arg)
  520. {
  521. ProfilerEntry *entry = (ProfilerEntry*) node;
  522. statscollector_t *collect = (statscollector_t*) arg;
  523. PyObject *info;
  524. int err;
  525. if (entry->callcount == 0)
  526. return 0; /* skip */
  527. if (entry->calls != EMPTY_ROTATING_TREE) {
  528. collect->sublist = PyList_New(0);
  529. if (collect->sublist == NULL)
  530. return -1;
  531. if (RotatingTree_Enum(entry->calls,
  532. statsForSubEntry, collect) != 0) {
  533. Py_DECREF(collect->sublist);
  534. return -1;
  535. }
  536. }
  537. else {
  538. Py_INCREF(Py_None);
  539. collect->sublist = Py_None;
  540. }
  541. info = PyObject_CallFunction((PyObject*) &StatsEntryType,
  542. "((OllddO))",
  543. entry->userObj,
  544. entry->callcount,
  545. entry->recursivecallcount,
  546. collect->factor * entry->tt,
  547. collect->factor * entry->it,
  548. collect->sublist);
  549. Py_DECREF(collect->sublist);
  550. if (info == NULL)
  551. return -1;
  552. err = PyList_Append(collect->list, info);
  553. Py_DECREF(info);
  554. return err;
  555. }
  556. PyDoc_STRVAR(getstats_doc, "\
  557. getstats() -> list of profiler_entry objects\n\
  558. \n\
  559. Return all information collected by the profiler.\n\
  560. Each profiler_entry is a tuple-like object with the\n\
  561. following attributes:\n\
  562. \n\
  563. code code object\n\
  564. callcount how many times this was called\n\
  565. reccallcount how many times called recursively\n\
  566. totaltime total time in this entry\n\
  567. inlinetime inline time in this entry (not in subcalls)\n\
  568. calls details of the calls\n\
  569. \n\
  570. The calls attribute is either None or a list of\n\
  571. profiler_subentry objects:\n\
  572. \n\
  573. code called code object\n\
  574. callcount how many times this is called\n\
  575. reccallcount how many times this is called recursively\n\
  576. totaltime total time spent in this call\n\
  577. inlinetime inline time (not in further subcalls)\n\
  578. ");
  579. static PyObject*
  580. profiler_getstats(ProfilerObject *pObj, PyObject* noarg)
  581. {
  582. statscollector_t collect;
  583. if (pending_exception(pObj))
  584. return NULL;
  585. if (!pObj->externalTimer)
  586. collect.factor = hpTimerUnit();
  587. else if (pObj->externalTimerUnit > 0.0)
  588. collect.factor = pObj->externalTimerUnit;
  589. else
  590. collect.factor = 1.0 / DOUBLE_TIMER_PRECISION;
  591. collect.list = PyList_New(0);
  592. if (collect.list == NULL)
  593. return NULL;
  594. if (RotatingTree_Enum(pObj->profilerEntries, statsForEntry, &collect)
  595. != 0) {
  596. Py_DECREF(collect.list);
  597. return NULL;
  598. }
  599. return collect.list;
  600. }
  601. static int
  602. setSubcalls(ProfilerObject *pObj, int nvalue)
  603. {
  604. if (nvalue == 0)
  605. pObj->flags &= ~POF_SUBCALLS;
  606. else if (nvalue > 0)
  607. pObj->flags |= POF_SUBCALLS;
  608. return 0;
  609. }
  610. static int
  611. setBuiltins(ProfilerObject *pObj, int nvalue)
  612. {
  613. if (nvalue == 0)
  614. pObj->flags &= ~POF_BUILTINS;
  615. else if (nvalue > 0) {
  616. #ifndef PyTrace_C_CALL
  617. PyErr_SetString(PyExc_ValueError,
  618. "builtins=True requires Python >= 2.4");
  619. return -1;
  620. #else
  621. pObj->flags |= POF_BUILTINS;
  622. #endif
  623. }
  624. return 0;
  625. }
  626. PyDoc_STRVAR(enable_doc, "\
  627. enable(subcalls=True, builtins=True)\n\
  628. \n\
  629. Start collecting profiling information.\n\
  630. If 'subcalls' is True, also records for each function\n\
  631. statistics separated according to its current caller.\n\
  632. If 'builtins' is True, records the time spent in\n\
  633. built-in functions separately from their caller.\n\
  634. ");
  635. static PyObject*
  636. profiler_enable(ProfilerObject *self, PyObject *args, PyObject *kwds)
  637. {
  638. int subcalls = -1;
  639. int builtins = -1;
  640. static char *kwlist[] = {"subcalls", "builtins", 0};
  641. if (!PyArg_ParseTupleAndKeywords(args, kwds, "|ii:enable",
  642. kwlist, &subcalls, &builtins))
  643. return NULL;
  644. if (setSubcalls(self, subcalls) < 0 || setBuiltins(self, builtins) < 0)
  645. return NULL;
  646. PyEval_SetProfile(profiler_callback, (PyObject*)self);
  647. self->flags |= POF_ENABLED;
  648. Py_INCREF(Py_None);
  649. return Py_None;
  650. }
  651. static void
  652. flush_unmatched(ProfilerObject *pObj)
  653. {
  654. while (pObj->currentProfilerContext) {
  655. ProfilerContext *pContext = pObj->currentProfilerContext;
  656. ProfilerEntry *profEntry= pContext->ctxEntry;
  657. if (profEntry)
  658. Stop(pObj, pContext, profEntry);
  659. else
  660. pObj->currentProfilerContext = pContext->previous;
  661. if (pContext)
  662. free(pContext);
  663. }
  664. }
  665. PyDoc_STRVAR(disable_doc, "\
  666. disable()\n\
  667. \n\
  668. Stop collecting profiling information.\n\
  669. ");
  670. static PyObject*
  671. profiler_disable(ProfilerObject *self, PyObject* noarg)
  672. {
  673. self->flags &= ~POF_ENABLED;
  674. PyEval_SetProfile(NULL, NULL);
  675. flush_unmatched(self);
  676. if (pending_exception(self))
  677. return NULL;
  678. Py_INCREF(Py_None);
  679. return Py_None;
  680. }
  681. PyDoc_STRVAR(clear_doc, "\
  682. clear()\n\
  683. \n\
  684. Clear all profiling information collected so far.\n\
  685. ");
  686. static PyObject*
  687. profiler_clear(ProfilerObject *pObj, PyObject* noarg)
  688. {
  689. clearEntries(pObj);
  690. Py_INCREF(Py_None);
  691. return Py_None;
  692. }
  693. static void
  694. profiler_dealloc(ProfilerObject *op)
  695. {
  696. if (op->flags & POF_ENABLED)
  697. PyEval_SetProfile(NULL, NULL);
  698. flush_unmatched(op);
  699. clearEntries(op);
  700. Py_XDECREF(op->externalTimer);
  701. Py_TYPE(op)->tp_free(op);
  702. }
  703. static int
  704. profiler_init(ProfilerObject *pObj, PyObject *args, PyObject *kw)
  705. {
  706. PyObject *o;
  707. PyObject *timer = NULL;
  708. double timeunit = 0.0;
  709. int subcalls = 1;
  710. #ifdef PyTrace_C_CALL
  711. int builtins = 1;
  712. #else
  713. int builtins = 0;
  714. #endif
  715. static char *kwlist[] = {"timer", "timeunit",
  716. "subcalls", "builtins", 0};
  717. if (!PyArg_ParseTupleAndKeywords(args, kw, "|Odii:Profiler", kwlist,
  718. &timer, &timeunit,
  719. &subcalls, &builtins))
  720. return -1;
  721. if (setSubcalls(pObj, subcalls) < 0 || setBuiltins(pObj, builtins) < 0)
  722. return -1;
  723. o = pObj->externalTimer;
  724. pObj->externalTimer = timer;
  725. Py_XINCREF(timer);
  726. Py_XDECREF(o);
  727. pObj->externalTimerUnit = timeunit;
  728. return 0;
  729. }
  730. static PyMethodDef profiler_methods[] = {
  731. {"getstats", (PyCFunction)profiler_getstats,
  732. METH_NOARGS, getstats_doc},
  733. {"enable", (PyCFunction)profiler_enable,
  734. METH_VARARGS | METH_KEYWORDS, enable_doc},
  735. {"disable", (PyCFunction)profiler_disable,
  736. METH_NOARGS, disable_doc},
  737. {"clear", (PyCFunction)profiler_clear,
  738. METH_NOARGS, clear_doc},
  739. {NULL, NULL}
  740. };
  741. PyDoc_STRVAR(profiler_doc, "\
  742. Profiler(custom_timer=None, time_unit=None, subcalls=True, builtins=True)\n\
  743. \n\
  744. Builds a profiler object using the specified timer function.\n\
  745. The default timer is a fast built-in one based on real time.\n\
  746. For custom timer functions returning integers, time_unit can\n\
  747. be a float specifying a scale (i.e. how long each integer unit\n\
  748. is, in seconds).\n\
  749. ");
  750. statichere PyTypeObject PyProfiler_Type = {
  751. PyObject_HEAD_INIT(NULL)
  752. 0, /* ob_size */
  753. "_lsprof.Profiler", /* tp_name */
  754. sizeof(ProfilerObject), /* tp_basicsize */
  755. 0, /* tp_itemsize */
  756. (destructor)profiler_dealloc, /* tp_dealloc */
  757. 0, /* tp_print */
  758. 0, /* tp_getattr */
  759. 0, /* tp_setattr */
  760. 0, /* tp_compare */
  761. 0, /* tp_repr */
  762. 0, /* tp_as_number */
  763. 0, /* tp_as_sequence */
  764. 0, /* tp_as_mapping */
  765. 0, /* tp_hash */
  766. 0, /* tp_call */
  767. 0, /* tp_str */
  768. 0, /* tp_getattro */
  769. 0, /* tp_setattro */
  770. 0, /* tp_as_buffer */
  771. Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE, /* tp_flags */
  772. profiler_doc, /* tp_doc */
  773. 0, /* tp_traverse */
  774. 0, /* tp_clear */
  775. 0, /* tp_richcompare */
  776. 0, /* tp_weaklistoffset */
  777. 0, /* tp_iter */
  778. 0, /* tp_iternext */
  779. profiler_methods, /* tp_methods */
  780. 0, /* tp_members */
  781. 0, /* tp_getset */
  782. 0, /* tp_base */
  783. 0, /* tp_dict */
  784. 0, /* tp_descr_get */
  785. 0, /* tp_descr_set */
  786. 0, /* tp_dictoffset */
  787. (initproc)profiler_init, /* tp_init */
  788. PyType_GenericAlloc, /* tp_alloc */
  789. PyType_GenericNew, /* tp_new */
  790. PyObject_Del, /* tp_free */
  791. };
  792. static PyMethodDef moduleMethods[] = {
  793. {NULL, NULL}
  794. };
  795. PyMODINIT_FUNC
  796. init_lsprof(void)
  797. {
  798. PyObject *module, *d;
  799. module = Py_InitModule3("_lsprof", moduleMethods, "Fast profiler");
  800. if (module == NULL)
  801. return;
  802. d = PyModule_GetDict(module);
  803. if (PyType_Ready(&PyProfiler_Type) < 0)
  804. return;
  805. PyDict_SetItemString(d, "Profiler", (PyObject *)&PyProfiler_Type);
  806. if (!initialized) {
  807. PyStructSequence_InitType(&StatsEntryType,
  808. &profiler_entry_desc);
  809. PyStructSequence_InitType(&StatsSubEntryType,
  810. &profiler_subentry_desc);
  811. }
  812. Py_INCREF((PyObject*) &StatsEntryType);
  813. Py_INCREF((PyObject*) &StatsSubEntryType);
  814. PyModule_AddObject(module, "profiler_entry",
  815. (PyObject*) &StatsEntryType);
  816. PyModule_AddObject(module, "profiler_subentry",
  817. (PyObject*) &StatsSubEntryType);
  818. empty_tuple = PyTuple_New(0);
  819. initialized = 1;
  820. }