Skip to content

Commit 2e52332

Browse files
committed
Merge rkern#76 from iddl/line_profiler
Feature: Add 'profile all' option
2 parents df8dfc8 + de1c1a7 commit 2e52332

File tree

2 files changed

+30
-0
lines changed

2 files changed

+30
-0
lines changed

_line_profiler.pyx

Lines changed: 18 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,13 +109,15 @@ cdef class LineProfiler:
109109
cdef public dict last_time
110110
cdef public double timer_unit
111111
cdef public long enable_count
112+
cdef public bint profile_all
112113

113114
def __init__(self, *functions):
114115
self.functions = []
115116
self.code_map = {}
116117
self.last_time = {}
117118
self.timer_unit = hpTimerUnit()
118119
self.enable_count = 0
120+
self.profile_all = False
119121
for func in functions:
120122
self.add_function(func)
121123

@@ -132,6 +134,16 @@ cdef class LineProfiler:
132134
self.code_map[code] = {}
133135
self.functions.append(func)
134136

137+
def enable_profile_all(self):
138+
""" Record line profiling information for all executed code.
139+
"""
140+
self.profile_all = True
141+
142+
def disable_profile_all(self):
143+
""" Disable recording line profiling information for all executed code.
144+
"""
145+
self.profile_all = False
146+
135147
def enable_by_count(self):
136148
""" Enable the profiler if it hasn't been enabled before.
137149
"""
@@ -198,6 +210,12 @@ cdef int python_trace_callback(object self_, PyFrameObject *py_frame, int what,
198210
self = <LineProfiler>self_
199211
last_time = self.last_time
200212

213+
if self.profile_all and what == PyTrace_CALL and <object>py_frame.f_code not in self.code_map:
214+
# enable recording profiling information for this function if
215+
# profile_all is enabled
216+
code = <object>py_frame.f_code
217+
self.code_map[code] = {}
218+
201219
if what == PyTrace_LINE or what == PyTrace_RETURN:
202220
code = <object>py_frame.f_code
203221
if code in self.code_map:

tests/test_line_profiler.py

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -60,6 +60,18 @@ def test_enable_disable(self):
6060
self.assertEqual(lp.enable_count, 0)
6161
self.assertEqual(lp.last_time, {})
6262

63+
def test_enable_profile_all(self):
64+
lp = LineProfiler()
65+
66+
lp.enable_profile_all()
67+
lp.enable()
68+
value = f(10)
69+
lp.disable()
70+
71+
self.assertEqual(value, f(10))
72+
self.assertEqual(len(lp.code_map.keys()), 1)
73+
self.assertEqual(len(lp.code_map[f.__code__]), 2)
74+
6375
def test_function_decorator(self):
6476
profile = LineProfiler()
6577
f_wrapped = profile(f)

0 commit comments

Comments
 (0)