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.
A stopwatch with perf_counter_ns
Section titled “A stopwatch with perf_counter_ns”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_nsfrom 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.439312took 19.177804 msThe 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.
Trap 1: the compiler deletes unused work
Section titled “Trap 1: the compiler deletes unused work”Watch what happens when you don’t use the result:
from std.time import perf_counter_nsfrom std.math import sqrtfrom 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 nswith keep: 18749454 nsTen 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 nsThe 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.
Run it many times with benchmark.run
Section titled “Run it many times with benchmark.run”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, Unitfrom 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: 70mean: 1.959 ms--------------------------------------------------------------------------------Benchmark Report (ms)--------------------------------------------------------------------------------Mean: 1.9586916285714286Total: 137.108414Iters: 70Warmup Total: 1.956134Fastest Mean: 1.9586916285714286Slowest Mean: 1.9586916285714286run(work, ...)takes a function with no arguments.workis a small closure that calls the real code withblack_boxandkeep.- 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.msandUnit.sare 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.
mainneedsraisesbecauseruncan raise.
One quick measurement with time_function
Section titled “One quick measurement with time_function”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_functionfrom std.benchmark import keep, black_boxfrom 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 nsThat’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?”.
Comparing two versions honestly
Section titled “Comparing two versions honestly”Most of the time you’re comparing: old code against new code, a plain loop against vectorize. A checklist that keeps the comparison fair:
- Check that both versions give the same answer (or close enough for floats) before timing anything. A fast wrong answer isn’t an improvement.
- Same input, realistic size. Make the data once, outside the timed function, and time both versions on it.
- Use
black_boxandkeep, so neither version gets optimized away. - 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. - 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.
Practice
Section titled “Practice”1. Time a list build
Section titled “1. Time a list build”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 mskeep(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.
2. Spot the fake benchmark
Section titled “2. Spot the fake benchmark”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_nsfrom 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_boxon inputs andkeepon results, and benchmark realistic code. benchmark.run(func, max_runtime_secs=...)warms up, repeats in batches and returns aReport(mean,iters,print). Withoutmax_runtime_secsit can take a minute.time_functiontimes 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
Section titled “Quick check”Quick check
Read more
Section titled “Read more”- benchmark module:
run,Report,Unit, and theBenchtools for bigger suites. - benchmark.run: every argument, including warmup and time limits.
- black_box: why benchmarks get optimized away, and how
black_boxandkeepstop it. - time module:
perf_counter_ns,monotonic,sleepandtime_function.