For beginners, focus on measuring performance first, then make small improvements in the areas that matter most.
Recommended practices:
- Measure before optimizing
- Performance includes CPU usage, memory consumption, power consumption, network and storage utilization, and animation performance.
- Make performance a regular part of development and testing instead of waiting until the app feels slow.
- Use profiling to find where time is spent
- In Visual Studio, Python profiling is available for Python 3.9 and earlier with a CPython-based interpreter.
- To profile code in Visual Studio:
- Open the Python code file.
- Confirm the interpreter is CPython-based.
- Select Debug > Launch Python Profiling.
- Choose either the whole project or a standalone script.
- Select Start and review the performance report.
- This helps identify which functions or parts of the program consume the most time.
- Reduce memory usage
- Lower memory usage improves app performance and overall system responsiveness.
- Good beginner habits include:
- reducing foreground memory usage,
- minimizing background work,
- releasing resources while the app is in the background,
- avoiding memory leaks.
- Dynamic memory is the more significant source of memory usage and where leaks usually appear.
- Benchmark without debugger overhead
- When comparing performance, run Python code with Debug > Start Without Debugging or Ctrl+F5.
- This avoids debugger overhead and gives a more realistic benchmark.
- Keep Python code correct and simple before optimizing
- Write the solution in pure Python first.
- After the code is correct, measure it and then optimize the slow parts.
- Consider native extensions only after profiling
- If a specific computation-heavy section is proven to be the bottleneck, a C++ extension can significantly improve speed.
- In the documented example, C++ routines ran about 5 to 20 times faster than the Python implementation.
- Also note that a debug build of a C++ module runs slower than a release build.
- Use a solid Windows Python setup
- A basic setup for learning on Windows is Python, Visual Studio Code, and the Python extension for VS Code.
- VS Code also provides Python support for editing, linting, debugging, and unit testing.
A simple beginner workflow is:
- write the program in pure Python,
- run it without debugging for timing,
- profile it if it is slow,
- reduce unnecessary memory use and background work,
- optimize only the parts proven to be slow.
- Windows app performance and fundamentals overview
- Improve app performance by reducing the use of memory and disk space
- Profile Python code in Visual Studio
- Create a C++ extension for Python in Visual Studio
- Create a C++ extension for Python in Visual Studio
- Set up your Python development environment on Windows
- Set up your Python development environment on Windows