Python: Zählen Sie, wie oft eine bestimmte Zeile ausgeführt wirdPython

Python-Programme
Anonymous
 Python: Zählen Sie, wie oft eine bestimmte Zeile ausgeführt wird

Post by Anonymous »

Problem < /h1>

Für pädagogische Zwecke möchte ich zählen, wie oft eine bestimmte Linie in einer bestimmten Funktion ausgeführt wird, ohne sie zu modifizieren oder zu dekorieren < /strong>. Zum Beispiel für die Funktion: < /p>

def binary_search(seq, x):
(a, b) = (0, len(seq) - 1)
while a seq[m]:
a = m + 1
else:
return m
< /code>

Ich würde einfach so etwas schreiben: < /p>

print count_exec(binary_search, range(100), 44, line_number = 4)
< /code>

... oder sogar so: < /p>

print count_exec(binary_search(range(100), 44), line = "m = (a + b) / 2")
< /code>

... die beide die Anzahl der 4. Zeile ausführen sollten (was 7). The ultimate goal is to provide an empirical approach to the complexity of any function:

Image


Non solutions

My current solution besteht darin, ein Funktionsattribut hinzuzufügen: < /p>

def binary_search(seq, x):
binary_search.count = 0 # : < /p>

erstellendef binary_search(seq, x):
(a, b) = (0, len(seq) - 1)
while a selbst zu dekorieren, aber für mich zählt dies so, dass es geändert wird. Es. < /li>
[*] Ich habe wenig Erfahrung in der Verwendung eines Python -Profilers. Es scheint ziemlich heftig für meine Bedürfnisse. Könnte es der richtige Weg sein?

Quick Reply

Change Text Case: 
   
  • Similar Topics
    Replies
    Views
    Last post