How do you get a Python profiler?

I try to follow the instructions here: http://docs.python.org/2/library/profile.html#module-cProfile

In particular, this part:

import cProfile, pstats, io
pr = cProfile.Profile()
pr.enable()
... do something ...
pr.disable()
s = io.StringIO()
ps = pstats.Stats(pr, stream=s)
ps.print_results()

I have already determined that print_results is not a real method of the Stats class, and it does not seem to exist anywhere. Here is my current code:

import cProfile, pstats, io
def foo(request):
    pr = cProfile.Profile()
    pr.enable()
    pass
    pr.disable()
    s = io.StringIO()
    ps = pstats.Stats(pr, stream = s)
    f = open('/profstats', 'a')
    ps.print_stats()
    f.write(s.getvalue())
    s.close()
    f.close()

Current result: TypeError at / inspection-summary / expected unicode argument, got 'str'

(The result looks like this because I use Django to call the code).

So does anyone know how I can actually get a profiler, well, work? I just want it to profile as intended, then print the results to a file so that I can view the results later after execution. I can make dump_stats work, but the file it creates is garbage.

+5
2

, API profile/pstats ad hoc. , ps.print_results() , .. ps.call_some_methods_to_print_the_result(), . dump_stats(), , .

, :

import cProfile, pstats
pr = cProfile.Profile()
pr.enable()
...
pr.disable()

f = open('x.prof', 'a')
sortby = 'cumulative'
pstats.Stats(pr, stream=f).strip_dirs().sort_stats(sortby).print_stats()
f.close()

sortby : , , , , , , nfl ( //), pcalls, stdname, .

+6

2.7 StringIO. , , . doc re StringIO

StringIO Unicode, 8- , . , 8- , 7- ASCII ( → 8- ), UnicodeError, getvalue().

getvalue() , , , pstats.py, , print_stats() :

 print >> self.stream, indent, self.total_calls, "function calls",

, , , StringIO , print_stats , - , , :

pr.enable()
(do the thing)
pr.disable()
pstats.Stats(pr).print_stats()

stdout , .

+5

All Articles