Linux command
cProfile 命令
网络
复制后可按需替换文件名、目录或参数。
常用示例
Profile a Python script
python -m cProfile [script.py]
Profile and sort by cumulative time
python -m cProfile -s cumtime [script.py]
Profile and save to file
python -m cProfile -o [profile.prof] [script.py]
Sort by total time in function
python -m cProfile -s tottime [script.py]
Profile specific function in code
import cProfile; cProfile.run('[function_call()]')
View saved profile with pstats
python -c "import pstats; p = pstats.Stats('[profile.prof]'); p.sort_stats('cumtime').print_stats(20)"
Visualize with snakeviz
snakeviz [profile.prof]
说明
cProfile is Python's built-in deterministic profiler that measures how much time is spent in each function. It's implemented in C for low overhead, making it suitable for profiling production code. The profiler tracks every function call and return, recording the number of calls and time spent. Output shows each function with call count, total time, time per call, cumulative time, and cumulative time per call. Profile data can be saved for later analysis with the pstats module or visualized with tools like snakeviz, pyprof2calltree, or gprof2dot. This enables detailed investigation of performance bottlenecks.
参数
- -o _file_
- Save profile statistics to file for later analysis.
- -s _sort_
- Sort output by specified column.
- -m _module_
- Profile a module run as a script (passed to python -m).
FAQ
What is the cProfile command used for?
cProfile is Python's built-in deterministic profiler that measures how much time is spent in each function. It's implemented in C for low overhead, making it suitable for profiling production code. The profiler tracks every function call and return, recording the number of calls and time spent. Output shows each function with call count, total time, time per call, cumulative time, and cumulative time per call. Profile data can be saved for later analysis with the pstats module or visualized with tools like snakeviz, pyprof2calltree, or gprof2dot. This enables detailed investigation of performance bottlenecks.
How do I run a basic cProfile example?
Run `python -m cProfile [script.py]` in a terminal, then adjust file names, paths, flags, or remote targets for your system.
What does -o _file_ do in cProfile?
Save profile statistics to file for later analysis.