Computing Elapsed Time in Zig 0.16.0
Measuring how long a piece of code takes to execute remains a fundamental task in systems programming. Developers use it for benchmarking, performance analysis, profiling, and implementing timeouts or delays. The original post demonstrated a simple approach using std.time.nanoTimestamp() on Zig 0.15.2. With the release of Zig 0.16.0, the Standard Library introduced a major overhaul of the I/O subsystem, and the recommended way to handle timestamps and elapsed time has evolved.
In Zig 0.16.0, the modern and flexible method relies on the new std.Io.Clock API, which integrates with the std.Io interface. This design provides better support for different clock types, cancellation, and both synchronous and asynchronous contexts.
Here is an updated, complete example that measures elapsed time using the new API:
const std = @import("std");
pub fn main(init: std.process.Init) !void {
const io = init.io;
const start = std.Io.Clock.now(.awake, io);
spendingComputerTime();
const end = std.Io.Clock.now(.awake, io);
const duration = start.durationTo(end);
std.debug.print("Elapsed time: {} ns\n", .{duration.toNanoseconds()});
std.debug.print("Elapsed time: {} ms\n", .{duration.toMilliseconds()});
}
fn spendingComputerTime() void {
var x: u64 = 0;
for (0..5_000_000) |i| {
x += i;
}
}
Key Changes in Zig 0.16.0 Link to heading
std.time.Timerand direct use ofstd.time.nanoTimestamp()in the old style are no longer the primary recommendation.- Timestamps come from
std.Io.Clock.now(clock_type, io), where common options include.awake(monotonic time that continues during suspension) or.real(wall-clock time). - The difference is calculated with
start.durationTo(end), which returns aDurationvalue. - Duration provides convenient methods such as
.toNanoseconds()and.toMilliseconds()for readable output. - The
main()function can now accept astd.process.Initparameter to obtain the io context easily. For more complex cases,std.Io.Threadedcan create an explicit I/O context.
Save the program as elapsedTime.zig and execute it as follows:
$ zig version
0.16.0
$ zig run elapsedTime.zig
Elapsed time: 12089958 ns
Elapsed time: 12 ms
Happy coding in Zig!