Problem For pedagogical purposes, I would like to count how many times a given line is executed in a given function without modifying or decorating it. For instance, for the function: def binary_search(seq, x): (a, b) = (0, len(seq) - 1) while a <= b: m = (a + b) / 2 if x < seq[m]: b = m - 1 elif x > seq[m]: a = m + 1 else: return m I would just write something like this: print count_exec(binary_search, range(100), 44, line_number = 4) ... or even like that: print count_exec(binary_search(range(100), 44), line = "m = (a + b) / 2") ... which both should print the number of times the 4th line is executed (which is 7). The ultimate goal is to provide an empirical approach to the complexity of any function: Non solutions My current solution consists in adding a function attribute: def binary_search(seq, x): binary_search.count = 0 # <------------------ added (a, b) = (0, len(seq) - 1) while a <= b: binary_search.count += 1 # <------------- added m = (a + b) / 2 if x < seq[m]: b = m - 1 elif x > seq[m]: a = m + 1 else: return m binary_search(range(100), 44) print binary_search.count I guess I could create a decorated function count_this_line: def binary_search(seq, x): (a, b) = (0, len(seq) - 1) while a <= b: count_this_line() # <-------------------- added m = (a + b) / 2 ... May be it is possible to decorate the function binary_search itself, but for me this counts as modifying it. Ideas The standard library ast can retrieve the abstract syntax tree of any given script, and even execute it. I have little experience in using a Python profiler. It seems quite heavy handed for my needs. Could it be the way to go? Continue reading...