Making Python programs blazingly fast
- Find what parts of your code are slowing down the program. A simple & lazy solution is to use a Unix time command. You can also use cProfile for detailed profiling.
- Once bottlenecks are identified, time the slow function without measuring the rest of the code.
- The most obvious way of making it faster is to use built-in data types.
- Caching or memoization with lru_cache will help improve functions that perform expensive I/O operations or some fairly slow recursive functions.
- You can improve performance, by using seemingly unnecessary assignments like local variables.
- You can also speed up your code just by wrapping the whole code in the main function and calling it once.
- Avoid or limit using dot operators (.) as they trigger dictionary lookup using getattribute, which creates extra overhead in your code.
- Operations on strings like modulus (%s) or .format() can get quite slow when running in a loop. Go for f-string instead which is the most readable, concise and fastest method.
Full post here, 5 mins read