authorgravatar for alex@alexrp.comAlex Rønne Petersen <alex@alexrp.com> 2025-02-21 01:01:52+01:00
committergravatar for alex@alexrp.comAlex Rønne Petersen <alex@alexrp.com> 2025-02-21 09:03:46+01:00
log31e7c95bd20801c6cb0cfbc47074333754f82ad5
tree686401dc5aace6049da51edaba695e25134ef5b9
parent8d9bb9746165abf067851f490cfea8c49fbd59ea

std.time: Make tests less flaky.

For the Timer decltest in particular, the margin check is not going to help if the kernel just decides not to schedule the thread for a while after we call timer.reset(). Failure observed here: https://github.com/ziglang/zig/actions/runs/13443634035/job/37563803341?pr=22909

1 files changed, 1 insertions(+), 11 deletions(-)

lib/std/time.zig+1-11
...@@ -74,15 +74,11 @@ pub fn nanoTimestamp() i128 {...@@ -74,15 +74,11 @@ pub fn nanoTimestamp() i128 {
74}74}
7575
76test milliTimestamp {76test milliTimestamp {
77 const margin = ns_per_ms * 50;
78
79 const time_0 = milliTimestamp();77 const time_0 = milliTimestamp();
80 std.Thread.sleep(ns_per_ms);78 std.Thread.sleep(ns_per_ms);
81 const time_1 = milliTimestamp();79 const time_1 = milliTimestamp();
82 const interval = time_1 - time_0;80 const interval = time_1 - time_0;
83 try testing.expect(interval > 0);81 try testing.expect(interval > 0);
84 // Tests should not depend on timings: skip test if outside margin.
85 if (!(interval < margin)) return error.SkipZigTest;
86}82}
8783
88// Divisions of a nanosecond.84// Divisions of a nanosecond.
...@@ -277,20 +273,14 @@ pub const Timer = struct {...@@ -277,20 +273,14 @@ pub const Timer = struct {
277};273};
278274
279test Timer {275test Timer {
280 const margin = ns_per_ms * 150;
281
282 var timer = try Timer.start();276 var timer = try Timer.start();
277
283 std.Thread.sleep(10 * ns_per_ms);278 std.Thread.sleep(10 * ns_per_ms);
284 const time_0 = timer.read();279 const time_0 = timer.read();
285 try testing.expect(time_0 > 0);280 try testing.expect(time_0 > 0);
286 // Tests should not depend on timings: skip test if outside margin.
287 if (!(time_0 < margin)) return error.SkipZigTest;
288281
289 const time_1 = timer.lap();282 const time_1 = timer.lap();
290 try testing.expect(time_1 >= time_0);283 try testing.expect(time_1 >= time_0);
291
292 timer.reset();
293 try testing.expect(timer.read() < time_1);
294}284}
295285
296test {286test {