Computing Elapsed Time in Zig

This simple Zig program demonstrates how to measure the execution time of a piece of code with nanosecond precision using the standard library’s built-in high-resolution timer.

const std = @import("std");

pub fn main() void {
    const start = std.time.nanoTimestamp();

    // The work that we want to measure
    spendingComputerTime();

    const end = std.time.nanoTimestamp();
    const elapsed_ns: i128 = end - start;

    std.debug.print("Elapsed time: {} ns\n", .{elapsed_ns});
    std.debug.print("Elapsed time: {} ms\n", .{@divTrunc(elapsed_ns, 1_000_000)});
}

fn spendingComputerTime() void {
    var x: u64 = 0;
    for (0..5_000_000) |i| {
        x += i;
    }
}

The program begins by importing the standard library with const std = @import("std");. In the main() function, it captures the current time in nanoseconds using std.time.nanoTimestamp() and stores it in start. It then calls spendingComputerTime(), which performs the actual work being measured: a loop that runs five million times (from 0 to 4,999,999), adding each iteration index i to a u64 variable x. This loop is deliberately CPU-intensive to create a noticeable delay.

After the function returns, a second timestamp is taken and stored in end. The elapsed time in nanoseconds is calculated by subtracting start from end and stored as an i128 to safely handle large values. Finally, std.debug.print outputs the elapsed time twice:

  • once directly in nanoseconds
  • once converted to milliseconds using @divTrunc(elapsed_ns, 1_000_000)

Save the program as elapsedTime.zig and run it as follows:

$ zig version
0.15.2
$ zig run elapsedTime.zig
Elapsed time: 11094000 ns
Elapsed time: 11 ms

Happy coding in Zig!