Hier ein weiteres Beispiel für Python 3 . Es werden zwei Funktionen verwendet, um zwei Zahlen zu addieren und dann CProfile zu verwenden, um das Ergebnis zu speichern. .prof
Datei. Dann lädt es die Speicherdatei mit pstats.Stats
und ```StringIO`` zur Umwandlung der Daten in eine Zeichenkette zur weiteren Verwendung.
main.py
import cProfile
import time
import pstats
from io import StringIO
def add_slow(a, b):
time.sleep(0.5)
return a+b
def add_fast(a, b):
return a+b
prof = cProfile.Profile()
def main_func():
arr = []
prof.enable()
for i in range(10):
if i%2==0:
arr.append(add_slow(i,i))
else:
arr.append(add_fast(i,i))
prof.disable()
#prof.print_stats(sort='time')
prof.dump_stats("main_funcs.prof")
return arr
main_func()
stream = StringIO();
stats = pstats.Stats("main_funcs.prof", stream=stream);
stats.print_stats()
stream.seek(0)
print(16*'=',"RESULTS",16*'=')
print (stream.read())
Verwendung:
python3 main.py
Ausgabe:
================ RESULTS ================
Tue Jul 6 17:36:21 2021 main_funcs.prof
26 function calls in 2.507 seconds
Random listing order was used
ncalls tottime percall cumtime percall filename:lineno(function)
10 0.000 0.000 0.000 0.000 {method 'append' of 'list' objects}
5 2.507 0.501 2.507 0.501 {built-in method time.sleep}
5 0.000 0.000 2.507 0.501 profiler.py:39(add_slow)
5 0.000 0.000 0.000 0.000 profiler.py:43(add_fast)
1 0.000 0.000 0.000 0.000 {method 'disable' of '_lsprof.Profiler' objects}
Kommentare: Wir können feststellen, dass die Funktion time.sleep im obigen Code etwa 2,507 Sekunden benötigt.