Skip to content

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.

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")
Terminal window
python3 collatz.py

On 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 s

and 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.

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 262

The 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")
Terminal window
mojo run collatz.mojo

On the same machine, three runs:

837799 525
took 0.357 s

and 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.

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: 9223372036854775807
plus one: -9223372036854775808

Collatz 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.

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 abort
from std.python import Python, PythonObject
from std.python.bindings import PythonModuleBuilder
@export
def 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, and Int(py=py_limit) turns it into a Mojo Int. 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_collatz registers the function under the name longest_collatz. The PyInit_ 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.importer
import 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:

Terminal window
uv run python compare.py

One run on our test machine:

Python: (837799, 525) 9.13 s
Mojo: (837799, 525) 0.31 s
Same answer: True
Mojo was 29 times faster

Over 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.

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_length

The 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 262

Same 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.

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.

  • Port the cached version to fast_collatz.mojo too, and add it to compare.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 the max package, 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.

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 9
27 112
837799 525

6 gives the 9 numbers from the start of this page. 837799 gives 525, matching the result of the big search.

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 9232
77671 1570824736

This 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, var and a main; the loop itself barely changes.
  • Mojo’s Int is 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, and import mojo.importer in 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

1. Why is the pure-Python loop slow?
2. What happens in Mojo when an Int goes past its biggest value?
3. Which line turns the Python argument into a Mojo Int?
4. What gave the biggest speedup for the pure-Python version on this page?