🌐
Blog
halvorsen.blog › documents › programming › python › resources › powerpoints › Optimization in Python.pdf pdf
Optimization in Python Hans-Petter Halvorsen https://www.halvorsen.blog
import scipy.optimize as opt · def banana(x): a = 1 · b = 100 · y = (a-x[0])**2 + b*(x[1]-x[0]**2)**2 · return y · xopt = opt.fmin(func=banana, x0=[-1.2,1]) print(xopt) Global minimum at (𝑥, 𝑦) = (𝑎, 𝑎)) Setting 𝑎= 1 gives global minimum at · (𝑥, 𝑦) = (1,1) The Python code gives the following ·
🌐
Stackify
stackify.com › how-to-optimize-python-code
Best Method of Python Code Optimization - Stackify - Ivanov
September 16, 2023 - Python code optimization is a way to make your program perform any task more efficiently and quickly with fewer lines of code, less memory, or other resources involved, while producing the right results.
Discussions

optimization - Speeding Up Python - Stack Overflow
This is really two questions, but they are so similar, and to keep it simple, I figured I'd just roll them together: Firstly: Given an established python project, what are some decent ways to speed... More on stackoverflow.com
🌐 stackoverflow.com
How to optimize python code?
Profiling. Don't even consider trying to optimise the performance of your code until you've got data on which stuff is slow. Most code isn't critical to performance, even in applications with hard-to-hit performance requirements, and it's a waste of time trying to tune the stuff that doesn't matter. Use a profiler to figure out which of your code is taking the most time, and once you know that, focus on that code. My favourite profiler right now is Py-Spy, but if you've only got the standard library at your disposal, cProfile is a good start. More on reddit.com
🌐 r/Python
157
177
January 28, 2022
Python code optimization
Hi! I’m writing a Python program to determine if a number n is abundant, that is, if its factors (excluding itself) have a sum greater than n. I know you can just use from sympy import divisors n = int(input()) if sum… More on discuss.python.org
🌐 discuss.python.org
0
0
April 1, 2024
Optimization Techniques in Python - Stack Overflow
Recently i have developed a billing application for my company with Python/Django. For few months everything was fine but now i am observing that the performance is dropping because of more and more More on stackoverflow.com
🌐 stackoverflow.com
🌐
Python
wiki.python.org › moin › PythonSpeed › PerformanceTips
PythonSpeed/PerformanceTips - Python Wiki
Also new since this was originally written are packages like Cython, Pyrex, Psyco, Weave, Shed Skin and PyInline, which can dramatically improve your application's performance by making it easier to push performance-critical code into C or machine language. Russian: http://omsk.lug.ru/wacko/PythonHacking/PerfomanceTips · You can only know what makes your program slow after first getting the program to give correct results, then running it to see if the correct program is slow. When found to be slow, profiling can show what parts of the program are consuming most of the time. A comprehensive but quick-to-run test suite can then ensure that future optimizations don't change the correctness of your program.
🌐
Python
python.org › doc › essays › list2str
Python Patterns - An Optimization Anecdote | Python.org
Try to use map(), filter() or reduce() to replace an explicit for loop, but only if you can use a built-in function: map with a built-in function beats for loop, but a for loop with in-line code beats map with a lambda function!
🌐
O'Reilly
oreilly.com › library › view › python-in-a › 0596100469 › ch18s04.html
Optimization - Python in a Nutshell, 2nd Edition [Book]
When performance is not acceptable, profiling often shows that all performance issues are in a small part of the code, perhaps 10 to 20 percent of the code where your program spends 80 or 90 percent of the time. Such performance-crucial regions of your code are ... Get Python in a Nutshell, 2nd Edition now with the O’Reilly learning platform.
🌐
Mobook
mobook.github.io › MO-book
Hands-On Mathematical Optimization with Python
We cannot provide a description for this page right now
🌐
Duke University
people.duke.edu › ~ccc14 › sta-663 › MakingCodeFast.html
Code Optimization — Computational Statistics in Python 0.1 documentation
Profiling means to time your code so as to identify bottelnecks. If one function is taking up 99% of the time in your program, it is sensiblt to focus on optimizign that function first.
🌐
ResearchGate
researchgate.net › publication › 390299425_Code_Optimization_Techniques_for_Improving_Execution_Time_in_Python
(PDF) Code Optimization Techniques for Improving Execution Time in Python
March 31, 2025 - Python is widely used for its simplicity and readabil- ity, but its interpreted nature can lead to performance limitations. This paper explores various code optimization techniques to enhance execution speed and efficiency.
Find elsewhere
🌐
Mobook
mobook.github.io › MO-book › intro.html
Hands-On Mathematical Optimization with Python — Companion code for the book "Hands-On Mathematical Optimization with Python"
Welcome to this repository of companion notebooks for the book Hands-On Mathematical Optimization with Python, published by Cambridge University Press.
Top answer
1 of 16
47

Regarding "Secondly: When writing a program from scratch in python, what are some good ways to greatly improve performance?"

Remember the Jackson rules of optimization:

  • Rule 1: Don't do it.
  • Rule 2 (for experts only): Don't do it yet.

And the Knuth rule:

  • "Premature optimization is the root of all evil."

The more useful rules are in the General Rules for Optimization.

  1. Don't optimize as you go. First get it right. Then get it fast. Optimizing a wrong program is still wrong.

  2. Remember the 80/20 rule.

  3. Always run "before" and "after" benchmarks. Otherwise, you won't know if you've found the 80%.

  4. Use the right algorithms and data structures. This rule should be first. Nothing matters as much as algorithm and data structure.

Bottom Line

You can't prevent or avoid the "optimize this program" effort. It's part of the job. You have to plan for it and do it carefully, just like the design, code and test activities.

2 of 16
30

Rather than just punting to C, I'd suggest:

Make your code count. Do more with fewer executions of lines:

  • Change the algorithm to a faster one. It doesn't need to be fancy to be faster in many cases.
  • Use python primitives that happens to be written in C. Some things will force an interpreter dispatch where some wont. The latter is preferable
  • Beware of code that first constructs a big data structure followed by its consumation. Think the difference between range and xrange. In general it is often worth thinking about memory usage of the program. Using generators can sometimes bring O(n) memory use down to O(1).
  • Python is generally non-optimizing. Hoist invariant code out of loops, eliminate common subexpressions where possible in tight loops.
  • If something is expensive, then precompute or memoize it. Regular expressions can be compiled for instance.
  • Need to crunch numbers? You might want to check numpy out.
  • Many python programs are slow because they are bound by disk I/O or database access. Make sure you have something worthwhile to do while you wait on the data to arrive rather than just blocking. A weapon could be something like the Twisted framework.
  • Note that many crucial data-processing libraries have C-versions, be it XML, JSON or whatnot. They are often considerably faster than the Python interpreter.

If all of the above fails for profiled and measured code, then begin thinking about the C-rewrite path.

🌐
Codefinity
codefinity.com › blog › Achieving-Peak-Performance-with-Python-Using-Optimization-Techniques
Achieving Peak Performance with Python Using Optimization Techniques
Learn how to optimize your Python code for better performance and efficiency by understanding Python's performance characteristics, profiling tools like cProfile, optimization techniques such as efficient data structures and algorithm selection, and utilizing built-in functions and libraries.
🌐
Syntha
syntha.ai › optimizers › python
Free Online Python Code Optimizer
Paste your Python code snippet in the input box and click the "Optimize" button.
🌐
Udemy
udemy.com › development
Python Code Optimization: Pro Techniques to Boost Code Speed
May 18, 2025 - Understanding Python Performance: Identify and analyze performance bottlenecks in your Python code. Measuring and Profiling: Learn to measure code execution and profile your applications using cProfile and dis.
Rating: 4.7 ​ - ​ 52 votes
🌐
Reddit
reddit.com › r/python › how to optimize python code?
r/Python on Reddit: How to optimize python code?
January 28, 2022 -

Hi Pythonistas,

I'm interested in learning what optimization techniques you know for python code. I know its a general statement, but I'm interested in really pushing execution to the maximum.

I use the following -

  1. I declare __slots__ in custom classes

  2. I use typing blocks for typing imports

  3. I use builtins when possible

  4. I try to reduce function calls

  5. I use set lookups wherever possible

  6. I prefer iteration to recursion

Edit: I am using a profiler, and benchmarks. I'm working on a library - an ASGI Api framework. The code is async. Its not darascience. Its neither compatible with pypy, nor with numba..

What else?

🌐
Analytics Vidhya
analyticsvidhya.com › back-channel › download-pdf.php pdf
Optimize Python Code for High-Speed Execution Introduction
Best practices highlighted the significance of vectorized code, minimizing memory allocation, optimizing · I/O operations, reducing global variables, and rigorous testing. The article equips developers to enhance · Python code across diverse applications, from image processing to machine learning and scientific
🌐
SOFTFORMANCE
softformance.com › home › blog › 25 tips for optimizing python performance
Optimizing Python Code for Performance: Tips & Tricks | SoftFormance
January 10, 2024 - For example, a developer can improve code readability by writing “a = 606024” to represent the number of seconds in a day. However, the language interpreter automatically calculates this and replaces repetitive instances, which, in turn, boosts software performance. If you are using Peephole optimization, Python precomputes constant expressions like 606024 and replaces them with the result, such as 86400.
🌐
Byu
acme.byu.edu › 0000017a-1bb8-db63-a97e-7bfa0be80000 › vol1lab18profiling-pdf pdf
Lab 1 Profiling and Optimizing Python Code Lab Objective:
Third, many non-Boolean objects in Python have truth values. For example, numbers are False when equal to zero and True otherwise. Similarly, lists and strings · are False when they are empty and True otherwise. So when a is a number, instead ... Problem 5. Using %prun, find out which portions of the code below require · the most runtime. Then, rewrite the function using some of the optimization...
🌐
Python.org
discuss.python.org › python help
Python code optimization - Python Help - Discussions on Python.org
April 1, 2024 - Hi! I’m writing a Python program to determine if a number n is abundant, that is, if its factors (excluding itself) have a sum greater than n. I know you can just use from sympy import divisors n = int(input()) if sum…
Top answer
1 of 9
11

As I said in comment, you must start by finding what part of your code is slow.

Nobody can help you without this information.

You can profile your code with the Python profilers then go back to us with the result.

If it's a Web app, the first suspect is generally the database. If it's a calculus intensive GUI app, then look first at the calculations algo first.

But remember that perf issues car be highly unintuitive and therefor, an objective assessment is the only way to go.

2 of 9
6

ok, not entirely to the point, but before you go and start fixing it, make sure everyone understands the situation. it seems to me that they're putting some pressure on you to fix the "problem".

well first of all, when you wrote the application, have they specified the performance requirements? did they tell you that they need operation X to take less than Y secs to complete? Did they specify how many concurrent users must be supported without penalty to the performance? If not, then tell them to back off and that it is iteration (phase, stage, whatever) one of the deployment, and the main goal was the functionality and testing. phase two is performance improvements. let them (with your help obviously) come up with some non functional requirements for the performance of your system.

by doing all this, a) you'll remove the pressure applied by the finance team (and i know they can be a real pain in the bum) b) both you and your clients will have a clear idea of what you mean by "performance" c) you'll have a base that you can measure your progress and most importantly d) you'll have some agreed time to implement/fix the performance issues.

PS. that aside, look at the indexing... :)