all Python 3cProfilefunction
cProfile.runctx()
running the profiler
Profiles a string of code with explicit globals and locals dictionaries — for code that needs local variables.
Syntax
cProfile.runctx(command, globals, locals, filename=None, sort=-1)
It fixes run()'s main problem: pass globals() and locals() and the code sees the caller's variables. It returns None, not the expression's result — if you need both the value and the profile, use Profile().runcall(func, *args). With filename the stats silently go to the file and nothing is printed.
Examples
import cProfile, pstats
def main():
data = list(range(1000))
result = cProfile.runctx('sorted(data)', globals(), locals(), 'out.prof')
print(result) # → None
print(pstats.Stats('out.prof').total_calls > 0) # → True
main()
See also
Open in the full glossarydocs.python.orgReport an inaccuracy