From the course: Faster Python Code

Always profile first - Python Tutorial

From the course: Faster Python Code

Start my 1-month free trial

Always profile first

- [Instructor] Here are the three rules of optimization. The first rule is don't. Most of the time, your code is fast enough. You should always have measurable performance goals before optimizing code. I've been in several situations where people told me, "make it as fast as you can." I usually answer this by saying, "okay, I'll get the team to create a special hardware then." Clarifying performance goal would effect the design of your system. The system that responds in one minute is very different than one that responds in one millisecond. After clarifying performance goals, you'll often find that Python is fast enough without any optimization at all. The second rule is don't yet. This rule usually means that since machine time is much cheaper than developer time, sometimes the solution is to get a better machine, faster network, or other solutions that don't involve changing code. The third rule is profile before optimizing. Profiling is the act of measuring where your code spends it's time. I've been doing code optimization for many years and the initial performance results still surprise me. Many times I found that the bottlenecks are in different place than the code I initially guessed. There are many tools for measuring how fast the code is running and where it spends it's time. Learning to use them effectively will make the process of finding your bottlenecks much easier. I'll also encourage you to read Rob Pike's Five Rules of Programming which is a very useful resource. One of the main takeaways is that bottlenecks occur in surprising places.

Contents