测量两个代码段之间的经过时间
Instant 表示相对于当前执行程序的时间戳,即使程序挂起它也会继续计时,可用于记录经过的时间。
调用 std.time.Instant.since 返回一个表示经过纳秒数的 u64。
这是一个非常常见的任务,为了方便起见,提供了一个 Timer。
const std = @import("std");
const time = std.time;
const Instant = time.Instant;
const Timer = time.Timer;
const print = std.debug.print;
fn expensive_function() void {
// sleep 500ms
std.Thread.sleep(time.ns_per_ms * 500);
}
pub fn main() !void {
// Method 1: Instant
const start = try Instant.now();
expensive_function();
const end = try Instant.now();
const elapsed1: f64 = @floatFromInt(end.since(start));
print("Time elapsed is: {d:.3}ms\n", .{
elapsed1 / time.ns_per_ms,
});
// Method 2: Timer
var timer = try Timer.start();
expensive_function();
const elapsed2: f64 = @floatFromInt(timer.read());
print("Time elapsed is: {d:.3}ms\n", .{
elapsed2 / time.ns_per_ms,
});
}