Skip to content

Mojo Benchmarking

“Is this faster?” is a question you can only answer by measuring. Guessing goes wrong all the time, and measuring badly goes wrong almost as often: the compiler is clever enough to skip work you thought you were timing. This page shows three ways to time code in Mojo, from a quick stopwatch to the benchmark module, and the traps that make numbers lie. Every timing here is from our test machine (a 4-core Linux VM). Run the examples yourself: your numbers will be different, and that’s expected.

perf_counter_ns() from std.time reads a high-resolution clock in nanoseconds. Read it before and after, and subtract:

from std.time import perf_counter_ns
from std.math import sqrt
def root_sum(n: Int) -> Float64:
var s: Float64 = 0
for i in range(n):
s += sqrt(Float64(i))
return s
def main():
var start = perf_counter_ns()
var result = root_sum(10_000_000)
var elapsed = perf_counter_ns() - start
print("result:", result)
print("took", Float64(elapsed) / 1_000_000, "ms")

You’ll see something like:

result: 21081849486.439312
took 19.177804 ms

The clock’s starting point means nothing on its own (it’s not the time of day), so only the difference between two readings is useful. A nanosecond is a billionth of a second; dividing by 1,000,000 gives milliseconds. In Python you’d use time.perf_counter_ns() the same way.

Watch what happens when you don’t use the result:

from std.time import perf_counter_ns
from std.math import sqrt
from std.benchmark import keep, black_box
def root_sum(n: Int) -> Float64:
var s: Float64 = 0
for i in range(n):
s += sqrt(Float64(i))
return s
def main():
var start = perf_counter_ns()
_ = root_sum(10_000_000)
print("result thrown away:", perf_counter_ns() - start, "ns")
start = perf_counter_ns()
keep(root_sum(black_box(10_000_000)))
print("with keep: ", perf_counter_ns() - start, "ns")

You’ll see something like this (three runs on our test machine gave 47, 125 and 96 ns for the first line):

result thrown away: 47 ns
with keep: 18749454 ns

Ten million square roots in 47 nanoseconds? No. The result was never used, so the optimizer removed the whole call, and you timed nothing. Two helpers from std.benchmark stop that:

  • keep(value) tells the compiler “pretend this value is used”, so the work that makes it stays.
  • black_box(value) hands back the same value but hides it from the optimizer, so it can’t use what it knows about it, like “n is always 10 million”.

Use black_box on inputs and keep on results. The black_box reference has a longer example.

Trap 2: the compiler does the math for you

Section titled “Trap 2: the compiler does the math for you”

Sometimes the optimizer doesn’t delete the work, it replaces it with something smarter:

from std.time import perf_counter_ns
def sum_to(n: Int) -> Int:
var total = 0
for i in range(n):
total += i
return total
def main():
var start = perf_counter_ns()
var result = sum_to(1_000_000_000)
var elapsed = perf_counter_ns() - start
print(result, "in", elapsed, "ns")

You’ll see something like:

499999999500000000 in 179 ns

The answer is right, and the result is used. But a billion additions don’t take 179 ns. The compiler recognized “add up 0 to n-1” and used the formula n * (n - 1) / 2 instead of the loop. black_box on n doesn’t change that, because the formula works for any n.

That’s not a bug; it’s the compiler doing its job. The lesson: benchmark code that looks like your real work, with realistic data. A toy loop can measure something your real program never does.

One measurement is noisy: the first call is often slower (memory isn’t warmed up yet), and other programs on your computer steal time. run from std.benchmark calls your function many times, in batches, and gives you a Report:

from std.benchmark import run, keep, black_box, Unit
from std.math import sqrt
def root_sum(n: Int) -> Float64:
var s: Float64 = 0
for i in range(n):
s += sqrt(Float64(i))
return s
def main() raises:
def work():
keep(root_sum(black_box(1_000_000)))
var report = run(work, max_runtime_secs=1.0)
print("runs:", report.iters())
print("mean:", round(report.mean(Unit.ms), 3), "ms")
report.print(Unit.ms)

You’ll see something like:

runs: 70
mean: 1.959 ms
--------------------------------------------------------------------------------
Benchmark Report (ms)
--------------------------------------------------------------------------------
Mean: 1.9586916285714286
Total: 137.108414
Iters: 70
Warmup Total: 1.956134
Fastest Mean: 1.9586916285714286
Slowest Mean: 1.9586916285714286
  • run(work, ...) takes a function with no arguments. work is a small closure that calls the real code with black_box and keep.
  • It runs a warmup first, which isn’t counted, then repeats in batches.
  • report.mean(Unit.ms) is the average time per call. Unit.ns, Unit.us (microseconds), Unit.ms and Unit.s are the choices.
  • “Fastest Mean” and “Slowest Mean” are the averages of the fastest and slowest batch, not of single calls. Here there was only one batch, so they’re all the same.
  • main needs raises because run can raise.

For a single timing without writing the subtraction yourself, time_function from std.time calls a function once and returns nanoseconds:

from std.time import time_function
from std.benchmark import keep, black_box
from std.math import sqrt
def root_sum(n: Int) -> Float64:
var s: Float64 = 0
for i in range(n):
s += sqrt(Float64(i))
return s
def main():
def work():
keep(root_sum(black_box(1_000_000)))
var ns = time_function(work)
print("one call took", ns, "ns")

You’ll see something like:

one call took 4187237 ns

That’s about 4.2 ms, while run measured 1.96 ms per call for the same work. The single call included the cold start that run’s warmup skips. A single number like this is fine for “is it about a second or about a minute?”, and not for “is version B 10% faster?”.

Most of the time you’re comparing: old code against new code, a plain loop against vectorize. A checklist that keeps the comparison fair:

  1. Check that both versions give the same answer (or close enough for floats) before timing anything. A fast wrong answer isn’t an improvement.
  2. Same input, realistic size. Make the data once, outside the timed function, and time both versions on it.
  3. Use black_box and keep, so neither version gets optimized away.
  4. Use run, not a single timing, and run the whole program two or three times. If the numbers jump around a lot, your computer is busy; close other programs.
  5. Report the machine. “0.13 ms on a 4-core VM with AVX-512” is useful. “4 times faster” alone isn’t, because it may not hold on another CPU.

The Mojo Vectorize and Mojo Parallelize lessons follow exactly this pattern. For bigger benchmark suites, the benchmark module also has Bench and Bencher, which run many named benchmarks and print a table or a CSV file; the benchmark module docs show them.

Time how long it takes to build a List[Int] with the numbers 0 to 999,999 using append, with benchmark.run. Print the mean in milliseconds.

Hint: inside the closure, build the list and pass len(xs) to keep, so the list isn’t optimized away. Remember max_runtime_secs.

Show solution
from std.benchmark import run, keep, Unit
def build() -> List[Int]:
var xs = List[Int]()
for i in range(1_000_000):
xs.append(i)
return xs^
def main() raises:
def work():
keep(len(build()))
var report = run(work, max_runtime_secs=1.0)
print("mean:", round(report.mean(Unit.ms), 3), "ms")

You’ll see something like (on our test machine):

mean: 0.996 ms

keep(len(build())) uses the result, so the compiler has to build the list. Your number will differ; the Mojo Performance Tips lesson shows how to make this faster.

This benchmark reports a time of a few nanoseconds. Explain why, and fix it.

from std.time import perf_counter_ns
def count_evens(n: Int) -> Int:
var c = 0
for i in range(n):
if i % 2 == 0:
c += 1
return c
def main():
var start = perf_counter_ns()
_ = count_evens(50_000_000)
print(perf_counter_ns() - start, "ns")

Hint: what happens to a result that’s assigned to _?

Show solution
from std.time import perf_counter_ns
from std.benchmark import keep, black_box
def count_evens(n: Int) -> Int:
var c = 0
for i in range(n):
if i % 2 == 0:
c += 1
return c
def main():
var start = perf_counter_ns()
keep(count_evens(black_box(50_000_000)))
print(perf_counter_ns() - start, "ns")

The result was thrown away, so the compiler skipped the call: on our test machine the broken version reported 101 ns. With keep the call has to happen, and the fixed version took about 16 to 18 ms there. black_box makes sure the compiler can’t work out the answer ahead of time from the constant 50,000,000.

  • perf_counter_ns() is a stopwatch: only the difference between two readings means anything.
  • The optimizer removes unused work and can replace loops with formulas. Use black_box on inputs and keep on results, and benchmark realistic code.
  • benchmark.run(func, max_runtime_secs=...) warms up, repeats in batches and returns a Report (mean, iters, print). Without max_runtime_secs it can take a minute.
  • time_function times one call; good for rough numbers, not for close comparisons.
  • Compare fairly: same answer, same input, many runs, and say which machine you measured on. Results vary between computers.

Next up: performance tips, the everyday habits that make Mojo code fast, and how to find the slow part of a program.

Quick check

1. Your benchmark says 10 million square roots took 50 ns. What is the most likely reason?
2. What does black_box(x) do?
3. You call run(work) with no other arguments on a function that takes 0.2 ms. What might happen?
4. Which is the best first step before comparing two versions of a function?

  • benchmark module: run, Report, Unit, and the Bench tools for bigger suites.
  • benchmark.run: every argument, including warmup and time limits.
  • black_box: why benchmarks get optimized away, and how black_box and keep stop it.
  • time module: perf_counter_ns, monotonic, sleep and time_function.