Project: Speed Up a Python Script
This is the project most Python developers come to Mojo for. You have a Python script, one function in it is slow, and you’d like that function to be fast without rewriting everything. In this project you’ll measure a slow function, port it to Mojo line by line, call the Mojo version from Python, and check both the answer and the speed. At the end there’s a twist that’s worth knowing before you port anything.
You’ll practise Mojo for Python developers, functions, tuples, integer overflow, calling Mojo from Python and benchmarking. Every number on this page is from our own runs, and we say on what machine.
The slow function
Section titled “The slow function”Our example is a classic puzzle. Take any positive whole number. If it’s even, halve it. If it’s odd, triple it and add 1. Repeat. The Collatz conjecture says you always reach 1 in the end. Starting from 6: 6, 3, 10, 5, 16, 8, 4, 2, 1. That’s a chain of 9 numbers.
The puzzle we’ll solve: which starting number below one million gives the longest chain? Here’s a plain Python answer, in collatz.py:
import time
def longest_collatz(limit): """Return (start, length) of the longest Collatz chain for starts below limit.""" best_start, best_length = 1, 1 for start in range(1, limit): n = start length = 1 while n != 1: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 length += 1 if length > best_length: best_start, best_length = start, length return best_start, best_length
start = time.perf_counter()print(longest_collatz(1_000_000))print(f"took {time.perf_counter() - start:.2f} s")python3 collatz.pyOn our test machine (a 4-core Linux VM with an Intel Xeon at 2.1 GHz, Python 3.13), three runs gave:
(837799, 525)took 8.94 sand 8.72 s and 8.84 s for the other two. Nearly 9 seconds. It’s the perfect candidate: a small function, simple types (whole numbers only), and almost all the time is spent in two nested loops. Python is slow at exactly this, because every n is a full Python object and every +, % and // goes through the interpreter.
Step 1: Port it to Mojo
Section titled “Step 1: Port it to Mojo”The Mojo version reads almost the same. Here it is with a smaller limit, so you can check the answer quickly:
def longest_collatz(limit: Int) -> Tuple[Int, Int]: var best_start = 1 var best_length = 1 for start in range(1, limit): var n = start var length = 1 while n != 1: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 length += 1 if length > best_length: best_start = start best_length = length return (best_start, best_length)
def main(): var result = longest_collatz(10_000) print(result[0], result[1])Output:
6171 262The changes from Python, one by one:
| Python | Mojo | Why |
|---|---|---|
def longest_collatz(limit): |
def longest_collatz(limit: Int) -> Tuple[Int, Int]: |
Mojo needs the argument and return types. |
n = start |
var n = start |
A new variable needs var. |
best_start, best_length = start, length |
two separate assignments | Plain and clear; no tuple needed. |
return best_start, best_length |
return (best_start, best_length) |
A tuple; read it back with result[0], result[1]. |
| the script’s top-level code | def main(): |
Mojo code must live in functions. |
Everything else, %, //, while, if, range, is the same. The Mojo for Python Developers lesson has the full list of differences.
Now change the limit to 1_000_000 and add a timer from std.time:
from std.time import perf_counter_ns
def longest_collatz(limit: Int) -> Tuple[Int, Int]: var best_start = 1 var best_length = 1 for start in range(1, limit): var n = start var length = 1 while n != 1: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 length += 1 if length > best_length: best_start = start best_length = length return (best_start, best_length)
def main(): var t0 = perf_counter_ns() var result = longest_collatz(1_000_000) var seconds = Float64(perf_counter_ns() - t0) / 1e9 print(result[0], result[1]) print("took", round(seconds, 3), "s")mojo run collatz.mojoOn the same machine, three runs:
837799 525took 0.357 sand 0.334 s and 0.377 s for the other two. Same answer, about 25 times faster than the Python version, from the same algorithm. The timer only covers the function call, not the few seconds mojo run spends compiling before the program starts.
Step 2: Check for overflow
Section titled “Step 2: Check for overflow”Before you trust a port, ask one question Python never makes you ask: do the numbers fit? A Python int grows as big as it needs to. A Mojo Int is 64 bits, and when it overflows it wraps around silently to a negative number, with no error (see Mojo Integer Overflow):
def main(): var n = 9223372036854775807 print("biggest Int:", n) print("plus one: ", n + 1)Output:
biggest Int: 9223372036854775807plus one: -9223372036854775808Collatz chains go up before they come down. We checked in Python: for starts below one million, the biggest number any chain reaches is 56,991,483,520, about 57 billion. The biggest Int is about 9.2 billion billion, so we’re safe by a wide margin. If you raise the limit a lot, check again. A wrong answer that looks right is the worst kind of bug.
Step 3: Call the Mojo version from Python
Section titled “Step 3: Call the Mojo version from Python”Running a separate Mojo program is fine for a test, but the real goal is to keep your Python script and swap only the slow function. Mojo can build a Python extension module: Python imports it like any other module. The Mojo Calling Mojo from Python lesson explains every line of the setup; here we use the same pattern.
Save this as fast_collatz.mojo:
from std.os import abortfrom std.python import Python, PythonObjectfrom std.python.bindings import PythonModuleBuilder
@exportdef PyInit_fast_collatz() abi("C") -> PythonObject: try: var m = PythonModuleBuilder("fast_collatz") m.def_function[longest_collatz]( "longest_collatz", docstring="Return (start, length) of the longest Collatz chain below limit.", ) return m.finalize() except e: abort(String("error creating the fast_collatz module:", e))
def longest_collatz(py_limit: PythonObject) raises -> PythonObject: var limit = Int(py=py_limit) var best_start = 1 var best_length = 1 for start in range(1, limit): var n = start var length = 1 while n != 1: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 length += 1 if length > best_length: best_start = start best_length = length return Python.tuple(best_start, best_length)Compared with Step 1, only the edges changed:
- The argument arrives as a
PythonObject, andInt(py=py_limit)turns it into a MojoInt. If Python passes something that isn’t a number, this raises, and Python sees an exception. Python.tuple(best_start, best_length)builds a real Python tuple, so the Python side gets(837799, 525), exactly what the old function returned.PyInit_fast_collatzregisters the function under the namelongest_collatz. ThePyInit_name must match the file name.
The loop in the middle is the same Mojo code as before. Now the Python side, compare.py, keeps its own version for comparison:
import time
import mojo.importerimport fast_collatz
def longest_collatz(limit): best_start, best_length = 1, 1 for start in range(1, limit): n = start length = 1 while n != 1: if n % 2 == 0: n = n // 2 else: n = 3 * n + 1 length += 1 if length > best_length: best_start, best_length = start, length return best_start, best_length
LIMIT = 1_000_000
start = time.perf_counter()py_result = longest_collatz(LIMIT)py_time = time.perf_counter() - start
start = time.perf_counter()mojo_result = fast_collatz.longest_collatz(LIMIT)mojo_time = time.perf_counter() - start
print("Python:", py_result, f"{py_time:.2f} s")print("Mojo: ", mojo_result, f"{mojo_time:.2f} s")print("Same answer:", py_result == mojo_result)print(f"Mojo was {py_time / mojo_time:.0f} times faster")import mojo.importer teaches Python to find .mojo files, so import fast_collatz compiles fast_collatz.mojo and loads it. Run it with the Python from your Mojo project, where uv add mojo installed the mojo package:
uv run python compare.pyOne run on our test machine:
Python: (837799, 525) 9.13 sMojo: (837799, 525) 0.31 sSame answer: TrueMojo was 29 times fasterOver three runs, Python took 9.13 to 9.50 s and Mojo 0.31 to 0.35 s, so between 26 and 29 times faster. The very first run also took about 7 extra seconds before anything printed: that’s Mojo compiling the module. The result is cached in a __mojocache__ folder, so later runs start right away until you change the .mojo file.
Step 4: The twist, a better algorithm
Section titled “Step 4: The twist, a better algorithm”Before you port anything, look at the algorithm. Our function recomputes the same chains over and over: the chain from 6 goes through 3, and we already computed the chain from 3. If we remember every length we’ve found, most chains stop early. Here’s that idea in Python:
def longest_collatz_cached(limit): lengths = [0] * limit lengths[1] = 1 best_start, best_length = 1, 1 for start in range(2, limit): n = start steps = 0 while n >= limit or lengths[n] == 0: n = n // 2 if n % 2 == 0 else 3 * n + 1 steps += 1 length = steps + lengths[n] lengths[start] = length if length > best_length: best_start, best_length = start, length return best_start, best_lengthThe while loop walks only until it reaches a number whose length we already know, then adds the steps it took. On our machine this pure Python version took 0.49 to 0.53 s for one million: about 17 times faster than the first Python version, and almost as fast as the simple Mojo port.
The same idea in Mojo:
def longest_collatz_cached(limit: Int) -> Tuple[Int, Int]: var lengths = List[Int](length=limit, fill=0) lengths[1] = 1 var best_start = 1 var best_length = 1 for start in range(2, limit): var n = start var steps = 0 while n >= limit or lengths[n] == 0: n = n // 2 if n % 2 == 0 else 3 * n + 1 steps += 1 var length = steps + lengths[n] lengths[start] = length if length > best_length: best_start = start best_length = length return (best_start, best_length)
def main(): var result = longest_collatz_cached(10_000) print(result[0], result[1])Output:
6171 262Same answer as Step 1. Timed with one million, as before, it took 0.026 to 0.031 s on our machine. Here’s everything side by side:
| Version | One million, our test VM |
|---|---|
| Python, simple | 8.7 to 9.5 s |
| Python, with the cache | 0.49 to 0.53 s |
| Mojo, simple | 0.31 to 0.38 s |
| Mojo, with the cache | 0.026 to 0.031 s |
The lesson: a better algorithm gave Python a bigger jump than switching language did, and doing both was the fastest by far. So fix the algorithm first, then move the hot loop to Mojo. Your numbers will be different on another machine; the order of the rows is what to look at.
Common mistakes
Section titled “Common mistakes”Forgetting py= when converting. Int(py_limit) doesn’t compile: converting a PythonObject needs the keyword, Int(py=py_limit). When the Mojo file doesn’t compile, Python’s import fails with an ImportError, and the real Mojo error is printed above it.
Running with the wrong Python. import mojo.importer needs the mojo package. The system python3 usually doesn’t have it, and fails with ModuleNotFoundError: No module named 'mojo'. Use uv run python compare.py, or activate your project’s environment first.
Timing the first run. The first import includes compiling the module. Time the function call, as compare.py does, not the whole script, and run it more than once.
Not checking the answer. A fast function that’s wrong is useless. Always compare the results, as Same answer: True does above.
Ideas to extend it
Section titled “Ideas to extend it”- Port the cached version to
fast_collatz.mojotoo, and add it tocompare.py. - Pass in a NumPy array instead of a single number, and return results for many inputs at once. The Mojo with NumPy lesson shows how data moves between them.
- Use all cores. The starts are independent, so you can split the range into chunks with
parallelize(from themaxpackage, see Mojo Parallelize) and combine the best result of each chunk. - Try your own slow function. Good candidates have simple number types and tight loops. Code that mostly calls other Python libraries won’t get faster by moving it.
Practice
Section titled “Practice”1. Chain length for one start
Section titled “1. Chain length for one start”Write def chain_length(start: Int) -> Int that returns the length of the chain from start (counting both start and the final 1), and print it for 6, 27 and 837799.
Hint: it’s the inner while loop from Step 1, on its own.
Show solution
def chain_length(start: Int) -> Int: var n = start var length = 1 while n != 1: n = n // 2 if n % 2 == 0 else 3 * n + 1 length += 1 return length
def main(): for start in [6, 27, 837799]: print(start, chain_length(start))Output:
6 927 112837799 5256 gives the 9 numbers from the start of this page. 837799 gives 525, matching the result of the big search.
2. The highest point
Section titled “2. The highest point”Write def highest_point(start: Int) -> Int that returns the biggest number reached in the chain from start. Print it for 27 and 77671.
Hint: keep a var top = start and update it with max(top, n) inside the loop.
Show solution
def highest_point(start: Int) -> Int: var n = start var top = start while n != 1: n = n // 2 if n % 2 == 0 else 3 * n + 1 top = max(top, n) return top
def main(): print(27, highest_point(27)) print(77671, highest_point(77671))Output:
27 923277671 1570824736This is the kind of check from Step 2: before trusting Int with a bigger search, find out how high the numbers really go.
- Measure first, and pick a small, hot function with simple types. Those gain the most from Mojo.
- A port is mostly adding types,
varand amain; the loop itself barely changes. - Mojo’s
Intis 64 bits and wraps silently. Check that your numbers fit before trusting the result. - To keep your Python script, build a module:
PyInit_<name>,Int(py=...)in,Python.tuple(...)out, andimport mojo.importerin Python. - Let Python call Mojo once with a lot of work, not many times with a little.
- On our test VM the simple port was about 25 to 29 times faster, but a better algorithm helped even more. Do both, and measure on your own machine.
Next up: Project: Matrix Multiplication, where you speed up a classic number-crunching loop step by step.
Quick check
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- Calling Mojo from Python: Mojo manual: the official guide to building Python modules in Mojo.
- PythonModuleBuilder: Mojo std library: adding functions and types to a module.
- Python: Mojo std library: helpers such as
Python.tupleandPython.import_module. - time.perf_counter: Python docs: the clock used on the Python side.