typestar

Timing a loop in Mojo

perf_counter_ns brackets a block of work to measure how long it really took.

from std.time import perf_counter_ns


def main():
    var start = perf_counter_ns()
    var total = 0
    for i in range(1000000):
        total += i * i
    var elapsed = perf_counter_ns() - start
    print("total", total)
    print("microseconds", elapsed // 1000)

How it works

  1. The counter is read once before the loop and once after it.
  2. The loop does enough work that the timer has something to see.
  3. Dividing the nanosecond difference by 1000 reports microseconds.

Keywords and builtins used here

The run, in numbers

Lines
11
Characters to type
235
Tokens
57
Three-star pace
75 tpm

At the three-star pace of 75 tokens a minute, this run takes about 46 seconds.

Type this snippet

Step 3 of 5 in Numbers & time, step 14 of 22 in Parameters & SIMD.

← Previous Next →