This repository contains a simple sampling-based profiler for Python programs. It periodically collects stack traces to analyze the performance of the code. The output can be directly converted to a FlameGraph using Brendan Greggs Flamegraph perl script. Don't be fooled by the simplicity, it is still very accurate and useful.
- Nothing to install. Python 3 is required.
from profiler import Sampler
def some_function():
b = 0
for i in range(100000000):
b += 1
def another_function():
c = 0
for i in range(100000000):
c += 1
def main():
# Initialize the sampler
sampler = Sampler()
# Start the sampler
sampler.start()
# Code to profile
some_function()
another_function()
# Output the collected statistics to a file
sampler.output_stats("example.stacks")
# Stop the sampler
sampler.stop()
if __name__ == "__main__":
main()The profiler will generate a .stacks file containing the profiling results that is directly readable by Brendan Gregg's Flamegraph program.
To convert the profiling output to a FlameGraph, follow these steps:
-
Ensure you have
FlameGraphtools installed. If not, clone the repository:git clone https://github.com/brendangregg/FlameGraph.git
-
Use the
flamegraph.plscript to generate the FlameGraph from the.stacksfile:./FlameGraph/flamegraph.pl example.stacks > example.svg -
Open the generated example.svg file in a web browser to visualize the FlameGraph.
This project is licensed under the MIT License.