You can use numba to JIT your current functions, which results in significant speed improvements (I've changed it to use numpy for ceil and sqrt as it is slightly faster than using math):

import numpy as np
import numba as nb

@nb.njit
def is_prime_number(number):
    if number % 2 == 0:
        return False
    root_of_number = np.ceil(np.sqrt(number))
    for i in range(3, root_of_number + 1, 2):
        if number % i == 0:
            return False
    return True

@nb.njit
def main(number):
    largest_prime_factor = 0

    for i in range(1, number + 1):
        if is_prime_number(i):
            if number % i == 0:
                if i > largest_prime_factor:
                    largest_prime_factor = i
        if i % 1000000 == 0:
            print(i)
    print(f"Largest prime factor of {number}: {largest_prime_factor}")

Timings:

%timeit main_op(7919)
%timeit main(7919)

Output:

3.83 ms ± 36.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
74.3 µs ± 245 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
Answer from user19393974 on Stack Overflow
🌐
Python
wiki.python.org › moin › PythonSpeed › PerformanceTips
PythonSpeed/PerformanceTips - Python Wiki
You should always test these tips with your application and the specific version of the Python implementation you intend to use and not just blindly accept that one method is faster than another. See the profiling section for more details. 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.
🌐
JetBrains
blog.jetbrains.com › pycharm › 2025 › 11 › 10-smart-performance-hacks-for-faster-python-code
10 Smart Performance Hacks For Faster Python Code | The PyCharm Blog
November 17, 2025 - Whenever possible, modify objects in place instead of creating duplicates. This reduces memory usage and improves performance by avoiding the overhead of allocating and populating new structures.
Discussions

Is there any way to increase the performance of my python code without using threads/processes? - Stack Overflow
I am trying to do the Euler Problems, and I am stuck on the Largest Prime Factor. I know how to work it out, but I am going about it in a brute-force manner. The files below are the two files in my More on stackoverflow.com
🌐 stackoverflow.com
I’m starting a series on Python performance optimizations, Looking for real-world use cases!
For API development utilizing async has to be at the top for me. Switching from synchronous to asynchronous has been a game changer for me, when I am choosing libraries I look for ones that have this capability if it’s not available then I look for ways to integrate it. One example is using taskiq over celery for sending longer tasks to worker nodes asynchronously. More on reddit.com
🌐 r/Python
60
69
August 23, 2025
Optimizing speed

Try Pandas, it handles tabular data much faster than iterating through of lists.

More on reddit.com
🌐 r/Python
17
2
August 12, 2018
When speed matters (10 Ways to Make Python Go Faster)
Those tipps mostly don't apply for production code, my thoughts on it, point by point: Optimise the innermost loop: Optimizing the innermost loop is a general advice, which doesn't only apply to python. If you're smart, try not to loop within loops and head for O(n) or O(log n) when possible. Function calls are expensive: Your code should be readable; function calls are a good way for future readability and maintainability Use built in types: Just try to stop using classes Leap before you look: Even though it is true the exeptions are somewhat expensive, you often can't get around them, e.g. the StopIteration in generators and the like, which is fine. Turn off automatic garbage collection: Turning of the GC is the easiest way to a memory hogging application, don't do it. If the GC is your problem, you've made some other mistake. Generally: Don't trade readability for a small performance boost If it must be fast, use numpy, pypy or something like stackless python. If that isn't fast enugh, well, don't use python. More on reddit.com
🌐 r/Python
54
61
August 24, 2013
🌐
Medium
medium.com › @quanticascience › performance-optimization-in-python-e8a497cdaf11
Performance Optimization in Python | by QuanticaScience | Medium
February 24, 2024 - In the realm of programming, Python stands out for its readability and ease of use, but it is often criticized for its performance. However, with the right techniques, Python’s performance can be significantly optimized. This article delves into various strategies for enhancing Python code efficiency, from understanding its performance characteristics to employing concurrency and advanced optimization techniques.
🌐
TheServerSide
theserverside.com › tip › Tips-to-improve-Python-performance
9 tips to improve Python performance | TheServerSide
This is a common Python performance tip: List comprehension will be faster than for loops.
🌐
Stackify
stackify.com › 20-simple-python-performance-tuning-tips
Python Performance Tuning: 20 Simple Tips - Stackify
May 2, 2023 - Python optimizes developer productivity, but many solutions aren't always optimized for python performance. Here are 20 tips to improve performance.
Top answer
1 of 3
3

You can use numba to JIT your current functions, which results in significant speed improvements (I've changed it to use numpy for ceil and sqrt as it is slightly faster than using math):

import numpy as np
import numba as nb

@nb.njit
def is_prime_number(number):
    if number % 2 == 0:
        return False
    root_of_number = np.ceil(np.sqrt(number))
    for i in range(3, root_of_number + 1, 2):
        if number % i == 0:
            return False
    return True

@nb.njit
def main(number):
    largest_prime_factor = 0

    for i in range(1, number + 1):
        if is_prime_number(i):
            if number % i == 0:
                if i > largest_prime_factor:
                    largest_prime_factor = i
        if i % 1000000 == 0:
            print(i)
    print(f"Largest prime factor of {number}: {largest_prime_factor}")

Timings:

%timeit main_op(7919)
%timeit main(7919)

Output:

3.83 ms ± 36.1 µs per loop (mean ± std. dev. of 7 runs, 100 loops each)
74.3 µs ± 245 ns per loop (mean ± std. dev. of 7 runs, 10000 loops each)
2 of 3
1

Also, for starters, you dont need to check all numbers up to "number+1". It is sufficient to test all numbers up to int(sqrt(number))+1. If you find a prime number, you divide your original number by that and repeat (recursively). At the end of this recursion, you will be left with some number which is itself prime and there will be no divisor found until sqrt(N). If that is the case, the number itself is a prime. I think with this method you will find primes quicker. E.g. for 3x7x7, you will just need 2+4+4 steps, instead of going through all the numbers. The last prime in the recursion should also be the largest prime factor, if I am not mistaken.

About code efficiency: Generally one should try to avoid for loops in python. I recommend you to look into e.g. the primefac module. I think you can get the full prime factorization of a number n by primefac.primefac(n) and then you can just pick its maximum (I am not too familiar with this module tho.)

🌐
SOFTFORMANCE
softformance.com › home › blog › 25 tips for optimizing python performance
Optimizing Python Code for Performance: Tips & Tricks | SoftFormance
January 10, 2024 - Later on, we will dwell on some useful tips on Python code compiling. Finally, Python code is dynamically typed. This means that you aren’t required to specify a data type every time you create a variable. This dynamic approach significantly boosts the speed of coding with Python, but it can also negatively impact Python’s performance if not managed properly.
Find elsewhere
🌐
DEV Community
dev.to › leapcell › python-performance-tips-you-must-know-24n5
Python Performance Tips You Must Know - DEV Community
January 29, 2025 - To improve performance, we should try to reduce unnecessary function calls and attempt to combine multiple operations into one, thereby reducing execution time and resource consumption.
🌐
GeeksforGeeks
geeksforgeeks.org › python › tips-to-maximize-your-python-code-performance
10 Tips to Maximize Your Python Code Performance - GeeksforGeeks
July 23, 2025 - Use built-in functions and libraries- Python has a lot of built-in functions and libraries that are highly optimized and can save you a lot of time and resources. Avoid using global variables-Global variables can slow down your code, as they ...
🌐
Reddit
reddit.com › r/python › i’m starting a series on python performance optimizations, looking for real-world use cases!
r/Python on Reddit: I’m starting a series on Python performance optimizations, Looking for real-world use cases!
August 23, 2025 -

Hey everyone,

I’m planning to start a series (not sure yet if it’ll be a blog, video, podcast, or something else) focused on Python performance. The idea is to explore concrete ways to:

  • Make Python code run faster

  • Optimize memory usage

  • Reduce infrastructure costs (e.g., cloud bills)

I’d love to base this on real-world use cases instead of just micro-benchmarks or contrived examples.

If you’ve ever run into performance issues in Python whether it’s slow scripts, web backends costing too much to run, or anything else I’d really appreciate if you could share your story.

These will serve as case studies for me to propose optimizations, compare approaches, and hopefully make the series valuable for the community.

Thanks in advance for any examples you can provide!

🌐
Scout APM
scoutapm.com › blog › python-performance-tips
15 Tips for Better Python Performance | Scout Monitoring
February 16, 2021 - So if you’re facing some very unusual spike in your performance metrics, it will be best to make sure that you’re running the latest version of Python, to be on the safe side. You can benchmark any piece of code that you want by using the methods that we described in the first tip.
🌐
AppSignal
blog.appsignal.com › 2025 › 05 › 28 › ways-to-optimize-your-code-in-python.html
Ways to Optimize Your Code in Python | AppSignal Blog
May 28, 2025 - In Python, dictionaries and sets are data structures that allow for fast lookups. When you want to check if an item is in a set or find a value associated with a key in a dictionary, these operations typically take constant time; this is denoted as O(1) in "Big O notation". Given their structure, using dictionaries and sets can significantly improve performance when you need to frequently check for the existence of an item or access elements by a key.
🌐
Medium
klaviyo.tech › how-to-improve-python-performance-6a43210f7359
How to Improve Python Performance | Klaviyo Engineering
December 19, 2022 - Tips, tricks, and techniques to optimize Python including NumPy, Scalene, Numba, Cython, and asyncio.
🌐
InfoWorld
infoworld.com › home › software development › programming languages › python
10 tips for speeding up Python programs | InfoWorld
May 14, 2025 - As with using C libraries, another important performance-enhancing tip is to keep the number of round trips to Cython to a minimum. Don’t write a loop that calls a “Cythonized” function repeatedly; implement the loop in Cython and pass the data all at once. Traditional Python apps—those implemented in CPython—execute only a single thread at a time, in order to avoid the problems of state that arise when using multiple threads.
🌐
ReviewNPrep
reviewnprep.com › blog › boosting-python-performance-10-essential-tips-and-tricks
Boosting Python Performance: 10 Essential Tips and Tricks – ReviewNPrep
By using generator expressions, you can save memory and increase performance, especially when dealing with large datasets or infinite sequences. # Example: Generating even numbers using a generator expression even_numbers = (x for x in range(1, 11) if x % 2 == 0) for num in even_numbers: print(num) Accessing variables in Python involves a lookup process that takes time.
🌐
HackerEarth
hackerearth.com › home › blog › 4 performance optimization tips for faster python code
Boosting Python Performance: 4 Optimization Tips for Faster Code
February 23, 2024 - To make your code run faster, the most important thing that you can do is to take two minutes before writing any code and think about the data-structure that you are going to use.
🌐
GitConnected
levelup.gitconnected.com › optimizing-python-performance-tips-and-tricks-for-faster-data-processing-38992cf57dcd
Optimizing Python Performance: Tips and Tricks for Faster Data Processing | by Tushar Aggarwal | Level Up Coding
August 30, 2024 - The first step in optimizing Python performance is identifying bottlenecks and slow parts of your code. Python provides several built-in profiling tools:
🌐
Binmile
binmile.com › blog › python-performance-optimization
Performance Optimization in Python: Tools & Techniques [2025 Guide]
February 10, 2025 - This article digs deep into several strategies to improve Python code efficiency, from grasping its performance traits to leveraging concurrency and advanced optimization techniques. Whether you are a naive or an accomplished developer, these details will help you write quicker and more efficient Python applications.
Address   2803 Philadelphia Pike, Suite B 191, 19703, Claymont
🌐
Crest Infotech
crestinfotech.com › home › optimizing python code for performance: tips and techniques for faster execution
Optimizing Python Code for Performance: Tips and Techniques for Faster Execution | Crest Infotech
February 11, 2025 - 1. Use Built-in Functions and Libraries Python’s built-in functions and libraries are optimized for performance. Whenever possible, use these built-in functions instead of writing custom code.