When trying to improve a slow function or module, it’s always a good idea to profile it. Here’s a snippet for quickly profiling a section of code with Python’s cProfile module, in two flavours. It’s adapted from the cProfile documentation’s Profile example. I have used versions of this snippet over the years to narrow in on performance issues.
Interesting… I’ve only ever done
python3 -m cProfile script.py
when I’ve had to profile some code.