all Python 3cProfilefunction
cProfile.run()
running the profiler
Profiles a string of code via exec() and prints a table: how many times each function ran and how much time it took.
Syntax
cProfile.run(command, filename=None, sort=-1)
The code runs in the namespace of the __main__ module, so the caller's local variables are invisible: cProfile.run('sorted(data)') inside main() raises NameError — use runctx() for them. With filename nothing is printed; the stats are saved to a binary file for pstats, not to text. sort='cumulative' shows straight away where time goes including nested calls.
Examples
import cProfile
def slow():
return sum(i * i for i in range(10000))
cProfile.run('slow()', sort='cumulative') # → ? таблица вызовов, время зависит от машины
import cProfile
def main():
data = list(range(1000))
try:
cProfile.run('sorted(data)')
except NameError as e:
print(e) # → name 'data' is not defined
main()
See also
Common errors
Open in the full glossarydocs.python.orgReport an inaccuracy