Programming Search⌘K

Taskintro

Sleep for a duration

Also called sleep, pause the program, wait for a number of seconds, delay, time.sleep, Thread.sleep, Task.Delay, setTimeout, nanosleep, sleep_for, asyncio.sleep, sleep in async code.

Pause the program for at least a given time. A sleep can end late or early, so loop to a deadline on a monotonic clock. In async code, use the sleep of the event loop.

Task

Pause the program for at least a given duration, for example 20 milliseconds, and then go on. In async code, pause only the current task and let the other tasks run.

Each language has a sleep function. Each one has the same three problems:

  • It can end late. The operating system wakes the thread when the time is up, but the thread can wait more before it runs. The Linux manual says that the interval "will be rounded up to the next multiple" of the granularity of the clock, and that "there may still be a delay before the CPU becomes free to once again execute the calling thread". So a sleep gives a minimum time, not an exact time.
  • It can end early. In C, a signal ends nanosleep early, and it "returns -1, sets errno to EINTR, and writes the remaining time" into its second argument. Some functions also take a smaller unit or a smaller range than the duration that you need, so one call cannot sleep for all of it.
  • It blocks. A sleep stops the whole thread. In async code, the thread also runs the other tasks, so they stop too.

The answer to the first two problems is a loop to a deadline. Read a monotonic clock, and add the duration to get the deadline. Then sleep for the rest of the time until the clock reaches the deadline:

now = clock()
deadline = now + duration
while now < deadline:
    sleep(deadline - now)
    now = clock()

A sleep that ends early is followed by a sleep for the rest of the time. A sleep that ends late ends the loop. Use a monotonic clock, which never goes back. A wall clock can jump when the system sets the time, and then the sleep is too short or too long. See Measure elapsed time.

A real sleep takes real time, so the contract tests the loop on a fake clock. sleep_requests(duration_ns, start_ns, readings) runs the loop with a clock that gives start_ns first and then the readings, one after each sleep. It returns the list of durations that the loop asks the sleep for, in nanoseconds. For example, a sleep of 1 ms from 0 that wakes at 0.6 ms asks for [1000000, 400000]. A duration of zero or less gives an empty list, with no sleep.

Each solution also has sleep_for(duration_ns), which runs the same loop with the real monotonic clock and the real sleep of the language. The test of each language sleeps for 20 ms and checks that at least 20 ms went by on the monotonic clock.

Solutions

  • Python. time.monotonic_ns() is the clock, and time.sleep(ns / 1e9) sleeps. The function sleeps at least the given time even if a signal interrupts it, unless the signal handler raises an exception. In async code, sleep_for_async uses await asyncio.sleep(...). The documentation says that "sleep() always suspends the current task, allowing other tasks to run".
  • JavaScript. There is no sleep that blocks. setTimeout from node:timers/promises returns a promise, and await suspends only the current function. process.hrtime.bigint() is the clock. The delay is in whole milliseconds, so the solution rounds the rest up, and it cuts the delay to 2147483647 ms. See the pitfalls.
  • TypeScript. The same code as JavaScript, with types.
  • Java. System.nanoTime() is the clock, and TimeUnit.NANOSECONDS.sleep(ns) sleeps. Thread.sleep throws InterruptedException if another thread interrupts the thread, and the solution passes it on to the caller. The documentation of nanoTime says to compare the difference of two readings, System.nanoTime() - startTime >= timeoutNanos, "because of the possibility of numerical overflow", so the loop compares deadline - now with zero.
  • C#. Stopwatch.GetTimestamp() is the clock. Thread.Sleep and Task.Delay take whole milliseconds, so the solution rounds the rest up and cuts it to int.MaxValue. SleepForAsync uses await Task.Delay(ms, cancel), which frees the thread and can be canceled.
  • Go. time.Sleep "pauses the current goroutine for at least the duration d". time.Since uses the monotonic reading of a time.Time. A goroutine that sleeps does not stop the other goroutines. SleepContext waits on a timer and on ctx.Done() with select, so a caller can cancel it.
  • Rust. Instant is the clock. std::thread::sleep "will never sleep less" than the duration. On Unix, "this function may invoke that system call multiple times". It "should not be used in async functions". The standard library has no async runtime, so the solution has no async version.
  • C. clock_gettime(CLOCK_MONOTONIC, ...) is the clock, and nanosleep sleeps. If a signal ends nanosleep early, the loop reads the clock and sleeps for the rest. On Linux, clock_nanosleep with TIMER_ABSTIME takes the deadline itself, and "If t is less than or equal to the current value of the clock, then clock_nanosleep() returns immediately".
  • C++. steady_clock is the clock, and std::this_thread::sleep_for "Blocks the execution of the current thread for at least the specified sleep_duration". std::this_thread::sleep_until(deadline) takes the deadline itself and "Blocks the execution of the current thread until specified sleep_time has been reached".
  • Bash. GNU sleep takes a number of seconds that can have a fraction: "NUMBER is an integer or floating-point". The function writes the nanoseconds as seconds with nine decimal places. Bash has no monotonic clock, so the function makes one call of sleep, and sleep_requests only shows the loop.

Most languages also have a sleep that a caller can cancel. In Go, select waits for the first of a timer and a context:

package main

import (
	"context"
	"fmt"
	"time"
)

func main() {
	ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
	defer cancel()
	start := time.Now()
	select {
	case <-time.After(time.Hour):
		fmt.Println("slept for an hour")
	case <-ctx.Done():
		fmt.Println(ctx.Err())
	}
	fmt.Println(time.Since(start) < time.Second)
}
Output
context deadline exceeded
true

Edge cases

The cases are in cases/basic.jsonl and cases/edge.jsonl.

  • zero, negative and most-negative: a duration of zero or less asks for no sleep. Some sleep functions throw for a negative value, and C# waits forever for -1. See the pitfalls.
  • woke-early, several-early-wakes and no-progress: each sleep that ends early is followed by a sleep for the rest. A wake with no progress of the clock asks for the same duration again.
  • woke-late, exact-deadline and extra-readings: a reading at or after the deadline ends the loop.
  • one-ns-short: a reading 1 ns before the deadline asks for one more sleep of 1 ns.
  • negative-origin and origin-after-100-days: the origin of a monotonic clock is arbitrary, so a reading can be negative or larger than 2^53. JavaScript uses bigint.
  • one-nanosecond and sub-millisecond: a sleep in whole milliseconds must round up. If it rounds 0.5 ms down to 0, the loop calls it again and again until the time is up.
  • one-hour and thirty-days: 30 days is more than 2147483647 ms, so the JavaScript and C# solutions sleep two times.

Pitfalls

  • A blocking sleep in async code. time.sleep in a coroutine stops the event loop, so two tasks sleep one after the other:

This code runs but gives a wrong answer on purpose.

import asyncio
import time


async def blocking():
    time.sleep(0.1)


async def suspending():
    await asyncio.sleep(0.1)


async def two(job):
    start = time.monotonic()
    await asyncio.gather(job(), job())
    return time.monotonic() - start


print("time.sleep, 0.2 s or more:", asyncio.run(two(blocking)) >= 0.2)
print("asyncio.sleep, 0.2 s or more:", asyncio.run(two(suspending)) >= 0.2)
Output
time.sleep, 0.2 s or more: True
asyncio.sleep, 0.2 s or more: False

The same is true for Thread.Sleep in a C# async method, and for std::thread::sleep in an async Rust function.

  • A delay larger than a timer can hold. Node.js says: "When delay is larger than 2147483647 or less than 1 or NaN, the delay will be set to 1." So a timer for 25 days fires at once, and Node.js writes only a warning to stderr:

This code runs but gives a wrong answer on purpose.

const start = performance.now();
setTimeout(() => {
  console.log("fired in less than 1 s:", performance.now() - start < 1000);
}, 2 ** 31);
Output
fired in less than 1 s: true

Node.js also says that "Non-integer delays are truncated to an integer", so a delay of 1.9 ms is 1 ms. Round up, and cut a long delay into parts.

  • -1 means forever in C#. Timeout.Infinite is -1, and Thread.Sleep throws ArgumentOutOfRangeException only if "The time-out value is negative and is not equal to Infinite". A duration that a subtraction makes -1 waits forever:

This code runs but gives a wrong answer on purpose.

using System.Threading;
using System.Threading.Tasks;

Console.WriteLine(Timeout.Infinite);
Console.WriteLine(Task.Delay(-1).Wait(100));
try
{
    Thread.Sleep(-2);
}
catch (ArgumentOutOfRangeException e)
{
    Console.WriteLine(e.GetType().Name);
}
Output
-1
False
ArgumentOutOfRangeException

Other languages differ for a negative duration too. Go says that "A negative or zero duration causes Sleep to return immediately". Java Thread.sleep throws IllegalArgumentException "if the value of millis is negative". Python raises ValueError:

This code runs but gives a wrong answer on purpose.

import time

try:
    time.sleep(-0.001)
except ValueError as e:
    print(type(e).__name__, e)
Output
ValueError sleep length must be non-negative

Check for a duration of zero or less before the call, as the loop does.

  • A sleep of the same length in a periodic loop drifts. A loop that does work and then sleeps for one period takes the period plus the time of the work on each pass, so it falls behind more and more. The Linux manual says the same of a sleep that restarts after a signal: "the time between the interruptions and restarts of the call will lead to drift in the time when the sleep finally completes. This problem can be avoided by using clock_nanosleep(2) with an absolute time value." Keep a deadline, add the period to it on each pass, and sleep until it.

  • A deadline on the wall clock. time.time(), Date.now() and System.currentTimeMillis() follow the time of day, which the system can set back or forward. Read a deadline on a monotonic clock.

Code

The build runs the native tests of each language in a pinned toolchain.

sleep.pyI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sleep-for-a-duration/.

import asyncio
import time
from collections.abc import Callable


def sleep_loop(duration_ns: int, clock: Callable[[], int], sleep: Callable[[int], None]) -> None:
    """Sleep until clock() reaches the deadline. A sleep that ends early is
    followed by a sleep for the rest of the time."""
    now = clock()
    deadline = now + duration_ns
    while now < deadline:
        sleep(deadline - now)
        now = clock()


def sleep_for(duration_ns: int) -> None:
    """Block the thread for at least duration_ns nanoseconds."""
    sleep_loop(duration_ns, time.monotonic_ns, lambda ns: time.sleep(ns / 1e9))


async def sleep_for_async(duration_ns: int) -> None:
    """Suspend the task for at least duration_ns nanoseconds. Other tasks run
    in the meantime."""
    now = time.monotonic_ns()
    deadline = now + duration_ns
    while now < deadline:
        await asyncio.sleep((deadline - now) / 1e9)
        now = time.monotonic_ns()


def sleep_requests(duration_ns: int, start_ns: int, readings: list[int]) -> list[int]:
    """Run sleep_loop on a fake clock and return the durations it asks for."""
    times = iter([start_ns, *readings])
    requests: list[int] = []
    sleep_loop(duration_ns, lambda: next(times), requests.append)
    return requests
test_sleep.py 58 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sleep-for-a-duration/.

import asyncio
import time

import pytest

from sleep import sleep_for, sleep_for_async, sleep_requests

CASES = [
    ("one-call", 1000000, 0, [1000000], [1000000]),
    ("woke-late", 1000000, 0, [1080000], [1000000]),
    ("woke-early", 1000000, 0, [600000, 1000000], [1000000, 400000]),
    ("one-second", 1000000000, 5000000000, [6000050000], [1000000000]),
    ("zero", 0, 0, [], []),
    ("negative", -5000000, 0, [], []),
    ("most-negative", -4611686018427387904, 0, [], []),
    ("several-early-wakes", 10000000, 0, [2000000, 5000000, 9999999, 10000000], [10000000, 8000000, 5000000, 1]),
    ("no-progress", 1000000, 0, [0, 1000000], [1000000, 1000000]),
    ("exact-deadline", 3000000, 100, [3000100], [3000000]),
    ("one-ns-short", 3000000, 0, [2999999, 3000000], [3000000, 1]),
    ("extra-readings", 1000000, 0, [1000000, 5000000], [1000000]),
    ("negative-origin", 2000000000, -5000000000, [-4000000000, -3000000000], [2000000000, 1000000000]),
    ("origin-after-100-days", 1500000, 8640000000000000, [8640000001000000, 8640000001500000], [1500000, 500000]),
    ("one-nanosecond", 1, 0, [1000000], [1]),
    ("sub-millisecond", 1500000, 0, [1000000, 1500000], [1500000, 500000]),
    ("one-hour", 3600000000000, 0, [3600000000000], [3600000000000]),
    ("thirty-days", 2592000000000000, 0, [2147483647000000, 2592000000000000], [2592000000000000, 444516353000000]),
]


@pytest.mark.parametrize(("name", "duration_ns", "start_ns", "readings", "want"), CASES, ids=[c[0] for c in CASES])
def test_sleep_requests(name, duration_ns, start_ns, readings, want):
    assert sleep_requests(duration_ns, start_ns, readings) == want


def test_sleep_for_waits_at_least_the_duration():
    start = time.monotonic_ns()
    sleep_for(20_000_000)
    assert time.monotonic_ns() - start >= 20_000_000


@pytest.mark.parametrize("duration_ns", [0, -5_000_000])
def test_sleep_for_returns_at_once(duration_ns):
    start = time.monotonic_ns()
    sleep_for(duration_ns)
    assert time.monotonic_ns() - start < 1_000_000_000


def test_sleep_for_async_lets_other_tasks_run():
    async def main():
        start = time.monotonic_ns()
        await asyncio.gather(sleep_for_async(100_000_000), sleep_for_async(100_000_000))
        return time.monotonic_ns() - start

    elapsed = asyncio.run(main())
    assert 100_000_000 <= elapsed < 200_000_000
sleep.hppI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

#ifndef SLEEP_FOR_A_DURATION_HPP
#define SLEEP_FOR_A_DURATION_HPP

#include <chrono>
#include <cstddef>
#include <thread>
#include <vector>

// Sleeps until clock() reaches the deadline. A sleep that ends early is
// followed by a sleep for the rest of the time.
template <class Clock, class Sleep>
void sleep_loop(long long duration_ns, Clock clock, Sleep sleep) {
    long long now = clock();
    const long long deadline = now + duration_ns;
    while (now < deadline) {
        sleep(deadline - now);
        now = clock();
    }
}

// Blocks the thread for at least duration_ns nanoseconds. steady_clock is
// monotonic, and sleep_for promises at least the duration that it gets.
inline void sleep_for_ns(long long duration_ns) {
    using namespace std::chrono;
    const auto clock = [] { return duration_cast<nanoseconds>(steady_clock::now().time_since_epoch()).count(); };
    sleep_loop(duration_ns, clock, [](long long ns) { std::this_thread::sleep_for(nanoseconds{ns}); });
}

// Runs sleep_loop on a fake clock and returns the durations it asks for.
inline std::vector<long long> sleep_requests(long long duration_ns, long long start_ns,
                                             const std::vector<long long>& readings) {
    std::vector<long long> times{start_ns};
    times.insert(times.end(), readings.begin(), readings.end());
    std::size_t next = 0;
    std::vector<long long> requests;
    sleep_loop(
        duration_ns, [&] { return times.at(next++); }, [&](long long ns) { requests.push_back(ns); });
    return requests;
}

#endif
test_sleep.cpp 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

#include <chrono>
#include <cstdio>
#include <vector>

#include "sleep.hpp"

namespace {

struct test_case {
    const char* name;
    long long duration_ns, start_ns;
    std::vector<long long> readings, want;
};

const test_case cases[] = {
    {"one-call", 1000000LL, 0LL, {1000000LL}, {1000000LL}},
    {"woke-late", 1000000LL, 0LL, {1080000LL}, {1000000LL}},
    {"woke-early", 1000000LL, 0LL, {600000LL, 1000000LL}, {1000000LL, 400000LL}},
    {"one-second", 1000000000LL, 5000000000LL, {6000050000LL}, {1000000000LL}},
    {"zero", 0LL, 0LL, {}, {}},
    {"negative", -5000000LL, 0LL, {}, {}},
    {"most-negative", -4611686018427387904LL, 0LL, {}, {}},
    {"several-early-wakes", 10000000LL, 0LL, {2000000LL, 5000000LL, 9999999LL, 10000000LL}, {10000000LL, 8000000LL, 5000000LL, 1LL}},
    {"no-progress", 1000000LL, 0LL, {0LL, 1000000LL}, {1000000LL, 1000000LL}},
    {"exact-deadline", 3000000LL, 100LL, {3000100LL}, {3000000LL}},
    {"one-ns-short", 3000000LL, 0LL, {2999999LL, 3000000LL}, {3000000LL, 1LL}},
    {"extra-readings", 1000000LL, 0LL, {1000000LL, 5000000LL}, {1000000LL}},
    {"negative-origin", 2000000000LL, -5000000000LL, {-4000000000LL, -3000000000LL}, {2000000000LL, 1000000000LL}},
    {"origin-after-100-days", 1500000LL, 8640000000000000LL, {8640000001000000LL, 8640000001500000LL}, {1500000LL, 500000LL}},
    {"one-nanosecond", 1LL, 0LL, {1000000LL}, {1LL}},
    {"sub-millisecond", 1500000LL, 0LL, {1000000LL, 1500000LL}, {1500000LL, 500000LL}},
    {"one-hour", 3600000000000LL, 0LL, {3600000000000LL}, {3600000000000LL}},
    {"thirty-days", 2592000000000000LL, 0LL, {2147483647000000LL, 2592000000000000LL}, {2592000000000000LL, 444516353000000LL}},
};

}  // namespace

int main() {
    using std::chrono::steady_clock;
    int failed = 0;
    for (const test_case& c : cases) {
        if (sleep_requests(c.duration_ns, c.start_ns, c.readings) != c.want) {
            std::printf("FAIL %s\n", c.name);
            failed = 1;
        }
    }
    auto start = steady_clock::now();
    sleep_for_ns(20'000'000);
    if (steady_clock::now() - start < std::chrono::milliseconds{20}) {
        std::printf("FAIL sleep_for_ns(20 ms) returned early\n");
        failed = 1;
    }
    for (const long long ns : {0LL, -5'000'000LL}) {
        start = steady_clock::now();
        sleep_for_ns(ns);
        if (steady_clock::now() - start >= std::chrono::seconds{1}) {
            std::printf("FAIL sleep_for_ns(%lld) did not return at once\n", ns);
            failed = 1;
        }
    }
    if (failed != 0) {
        return 1;
    }
    std::printf("ok\n");
    return 0;
}
Sleep.javaI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;

/** Sleeps for a duration on a monotonic clock. */
public final class Sleep {
    private Sleep() {}

    /** A monotonic clock in nanoseconds. */
    @FunctionalInterface
    public interface Clock {
        long nanos();
    }

    /** A sleep for a number of nanoseconds. */
    @FunctionalInterface
    public interface Sleeper {
        void sleep(long nanos) throws InterruptedException;
    }

    /**
     * Sleeps until the clock reaches the deadline. A sleep that ends early is followed by a sleep
     * for the rest of the time. The loop compares the difference with zero, as the documentation
     * of System.nanoTime advises, because of the possibility of numerical overflow.
     */
    public static void sleepLoop(long durationNs, Clock clock, Sleeper sleeper) throws InterruptedException {
        long now = clock.nanos();
        long deadline = now + durationNs;
        while (deadline - now > 0) {
            sleeper.sleep(deadline - now);
            now = clock.nanos();
        }
    }

    /** Blocks the thread for at least durationNs nanoseconds. */
    public static void sleepFor(long durationNs) throws InterruptedException {
        sleepLoop(durationNs, System::nanoTime, TimeUnit.NANOSECONDS::sleep);
    }

    /** Runs sleepLoop on a fake clock and returns the durations it asks for. */
    public static long[] sleepRequests(long durationNs, long startNs, long[] readings) {
        long[] times = new long[readings.length + 1];
        times[0] = startNs;
        System.arraycopy(readings, 0, times, 1, readings.length);
        int[] next = {0};
        List<Long> requests = new ArrayList<>();
        try {
            sleepLoop(durationNs, () -> times[next[0]++], requests::add);
        } catch (InterruptedException e) {
            throw new IllegalStateException("the fake sleep does not throw", e);
        }
        return requests.stream().mapToLong(Long::longValue).toArray();
    }
}
SleepTest.java 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

import static org.junit.jupiter.api.Assertions.assertArrayEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;

import java.util.stream.Stream;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.Arguments;
import org.junit.jupiter.params.provider.MethodSource;

class SleepTest {
    static Stream<Arguments> cases() {
        return Stream.of(
                Arguments.of("one-call", 1000000L, 0L, new long[] {1000000L}, new long[] {1000000L}),
                Arguments.of("woke-late", 1000000L, 0L, new long[] {1080000L}, new long[] {1000000L}),
                Arguments.of("woke-early", 1000000L, 0L, new long[] {600000L, 1000000L}, new long[] {1000000L, 400000L}),
                Arguments.of("one-second", 1000000000L, 5000000000L, new long[] {6000050000L}, new long[] {1000000000L}),
                Arguments.of("zero", 0L, 0L, new long[] {}, new long[] {}),
                Arguments.of("negative", -5000000L, 0L, new long[] {}, new long[] {}),
                Arguments.of("most-negative", -4611686018427387904L, 0L, new long[] {}, new long[] {}),
                Arguments.of("several-early-wakes", 10000000L, 0L, new long[] {2000000L, 5000000L, 9999999L, 10000000L}, new long[] {10000000L, 8000000L, 5000000L, 1L}),
                Arguments.of("no-progress", 1000000L, 0L, new long[] {0L, 1000000L}, new long[] {1000000L, 1000000L}),
                Arguments.of("exact-deadline", 3000000L, 100L, new long[] {3000100L}, new long[] {3000000L}),
                Arguments.of("one-ns-short", 3000000L, 0L, new long[] {2999999L, 3000000L}, new long[] {3000000L, 1L}),
                Arguments.of("extra-readings", 1000000L, 0L, new long[] {1000000L, 5000000L}, new long[] {1000000L}),
                Arguments.of("negative-origin", 2000000000L, -5000000000L, new long[] {-4000000000L, -3000000000L}, new long[] {2000000000L, 1000000000L}),
                Arguments.of("origin-after-100-days", 1500000L, 8640000000000000L, new long[] {8640000001000000L, 8640000001500000L}, new long[] {1500000L, 500000L}),
                Arguments.of("one-nanosecond", 1L, 0L, new long[] {1000000L}, new long[] {1L}),
                Arguments.of("sub-millisecond", 1500000L, 0L, new long[] {1000000L, 1500000L}, new long[] {1500000L, 500000L}),
                Arguments.of("one-hour", 3600000000000L, 0L, new long[] {3600000000000L}, new long[] {3600000000000L}),
                Arguments.of("thirty-days", 2592000000000000L, 0L, new long[] {2147483647000000L, 2592000000000000L}, new long[] {2592000000000000L, 444516353000000L}));
    }

    @ParameterizedTest(name = "{0}")
    @MethodSource("cases")
    void sleepRequests(String name, long durationNs, long startNs, long[] readings, long[] want) {
        assertArrayEquals(want, Sleep.sleepRequests(durationNs, startNs, readings), name);
    }

    @Test
    void sleepForWaitsAtLeastTheDuration() throws InterruptedException {
        long start = System.nanoTime();
        Sleep.sleepFor(20_000_000L);
        assertTrue(System.nanoTime() - start >= 20_000_000L);
    }

    @Test
    void sleepForReturnsAtOnce() throws InterruptedException {
        for (long ns : new long[] {0L, -5_000_000L}) {
            long start = System.nanoTime();
            Sleep.sleepFor(ns);
            assertTrue(System.nanoTime() - start < 1_000_000_000L);
        }
    }
}
sleep.cI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

#define _POSIX_C_SOURCE 200809L

#include "sleep.h"

#include <time.h>

void sleep_loop(int64_t duration_ns, sleep_clock_fn clock, sleep_fn sleep, void *ctx) {
    int64_t now = clock(ctx);
    const int64_t deadline = now + duration_ns;
    while (now < deadline) {
        sleep(ctx, deadline - now);
        now = clock(ctx);
    }
}

static int64_t monotonic_ns(void *ctx) {
    (void)ctx;
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return (int64_t)t.tv_sec * 1000000000 + t.tv_nsec;
}

// One call of nanosleep. A signal can end it early with EINTR. The loop then
// reads the clock and sleeps for the rest, so the error needs no handling.
static void nanosleep_ns(void *ctx, int64_t ns) {
    (void)ctx;
    const struct timespec d = {.tv_sec = (time_t)(ns / 1000000000), .tv_nsec = (long)(ns % 1000000000)};
    (void)nanosleep(&d, NULL);
}

void sleep_for_ns(int64_t duration_ns) {
    sleep_loop(duration_ns, monotonic_ns, nanosleep_ns, NULL);
}

struct fake {
    int64_t start_ns;
    const int64_t *readings;
    size_t n, next;
    int64_t *out;
    size_t cap, count;
};

static int64_t fake_clock(void *ctx) {
    struct fake *f = ctx;
    if (f->next == 0) {
        f->next = 1;
        return f->start_ns;
    }
    // The contract gives enough readings. If they run out, the clock jumps to
    // the end of time, so that the loop stops.
    const size_t i = f->next - 1;
    f->next++;
    return i < f->n ? f->readings[i] : INT64_MAX;
}

static void fake_sleep(void *ctx, int64_t ns) {
    struct fake *f = ctx;
    if (f->count < f->cap) {
        f->out[f->count] = ns;
    }
    f->count++;
}

size_t sleep_requests(int64_t duration_ns, int64_t start_ns, const int64_t *readings, size_t n,
                      int64_t *out, size_t cap) {
    struct fake f = {start_ns, readings, n, 0, out, cap, 0};
    sleep_loop(duration_ns, fake_clock, fake_sleep, &f);
    return f.count < cap ? f.count : cap;
}
sleep.h 28 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

#ifndef SLEEP_FOR_A_DURATION_H
#define SLEEP_FOR_A_DURATION_H

#include <stddef.h>
#include <stdint.h>

// A monotonic clock in nanoseconds, and a sleep for a number of nanoseconds.
// ctx is the state of a fake clock and a fake sleep, or NULL.
typedef int64_t (*sleep_clock_fn)(void *ctx);
typedef void (*sleep_fn)(void *ctx, int64_t ns);

// Sleeps until clock reaches the deadline. A sleep that ends early is
// followed by a sleep for the rest of the time.
void sleep_loop(int64_t duration_ns, sleep_clock_fn clock, sleep_fn sleep, void *ctx);

// Blocks the thread for at least duration_ns nanoseconds on CLOCK_MONOTONIC.
void sleep_for_ns(int64_t duration_ns);

// Runs sleep_loop on a fake clock that gives start_ns and then the n
// readings. Writes the durations that the loop asks for to out, at most cap
// of them, and returns their number.
size_t sleep_requests(int64_t duration_ns, int64_t start_ns, const int64_t *readings, size_t n,
                      int64_t *out, size_t cap);

#endif
test_sleep.c 80 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

#define _POSIX_C_SOURCE 200809L

#include "sleep.h"

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

struct test_case {
    const char *name;
    long long duration_ns, start_ns;
    size_t n;
    int64_t readings[4];
    size_t want_n;
    int64_t want[4];
};

static const struct test_case cases[] = {
    {"one-call", 1000000LL, 0LL, 1, {1000000LL}, 1, {1000000LL}},
    {"woke-late", 1000000LL, 0LL, 1, {1080000LL}, 1, {1000000LL}},
    {"woke-early", 1000000LL, 0LL, 2, {600000LL, 1000000LL}, 2, {1000000LL, 400000LL}},
    {"one-second", 1000000000LL, 5000000000LL, 1, {6000050000LL}, 1, {1000000000LL}},
    {"zero", 0LL, 0LL, 0, {0}, 0, {0}},
    {"negative", -5000000LL, 0LL, 0, {0}, 0, {0}},
    {"most-negative", -4611686018427387904LL, 0LL, 0, {0}, 0, {0}},
    {"several-early-wakes", 10000000LL, 0LL, 4, {2000000LL, 5000000LL, 9999999LL, 10000000LL}, 4, {10000000LL, 8000000LL, 5000000LL, 1LL}},
    {"no-progress", 1000000LL, 0LL, 2, {0LL, 1000000LL}, 2, {1000000LL, 1000000LL}},
    {"exact-deadline", 3000000LL, 100LL, 1, {3000100LL}, 1, {3000000LL}},
    {"one-ns-short", 3000000LL, 0LL, 2, {2999999LL, 3000000LL}, 2, {3000000LL, 1LL}},
    {"extra-readings", 1000000LL, 0LL, 2, {1000000LL, 5000000LL}, 1, {1000000LL}},
    {"negative-origin", 2000000000LL, -5000000000LL, 2, {-4000000000LL, -3000000000LL}, 2, {2000000000LL, 1000000000LL}},
    {"origin-after-100-days", 1500000LL, 8640000000000000LL, 2, {8640000001000000LL, 8640000001500000LL}, 2, {1500000LL, 500000LL}},
    {"one-nanosecond", 1LL, 0LL, 1, {1000000LL}, 1, {1LL}},
    {"sub-millisecond", 1500000LL, 0LL, 2, {1000000LL, 1500000LL}, 2, {1500000LL, 500000LL}},
    {"one-hour", 3600000000000LL, 0LL, 1, {3600000000000LL}, 1, {3600000000000LL}},
    {"thirty-days", 2592000000000000LL, 0LL, 2, {2147483647000000LL, 2592000000000000LL}, 2, {2592000000000000LL, 444516353000000LL}},
};

static int64_t now_ns(void) {
    struct timespec t;
    clock_gettime(CLOCK_MONOTONIC, &t);
    return (int64_t)t.tv_sec * 1000000000 + t.tv_nsec;
}

int main(void) {
    int failed = 0;
    for (size_t i = 0; i < sizeof cases / sizeof cases[0]; i++) {
        const struct test_case *c = &cases[i];
        int64_t got[8];
        const size_t n = sleep_requests(c->duration_ns, c->start_ns, c->readings, c->n, got, 8);
        if (n != c->want_n || memcmp(got, c->want, n * sizeof got[0]) != 0) {
            printf("FAIL %s: got %zu requests\n", c->name, n);
            failed = 1;
        }
    }
    int64_t start = now_ns();
    sleep_for_ns(20000000);
    if (now_ns() - start < 20000000) {
        printf("FAIL sleep_for_ns(20 ms) returned early\n");
        failed = 1;
    }
    const int64_t at_once[] = {0, -5000000};
    for (size_t i = 0; i < 2; i++) {
        start = now_ns();
        sleep_for_ns(at_once[i]);
        if (now_ns() - start >= 1000000000) {
            printf("FAIL sleep_for_ns(%lld) did not return at once\n", (long long)at_once[i]);
            failed = 1;
        }
    }
    if (failed) {
        return EXIT_FAILURE;
    }
    printf("ok\n");
    return EXIT_SUCCESS;
}
Sleep.csI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;

/// <summary>Sleeps for a duration on a monotonic clock.</summary>
public static class Sleep
{
    /// <summary>
    /// Sleeps until the clock reaches the deadline. A sleep that ends early is followed by a sleep
    /// for the rest of the time.
    /// </summary>
    public static void SleepLoop(long durationNs, Func<long> clock, Action<long> sleep)
    {
        long now = clock();
        long deadline = now + durationNs;
        while (now < deadline)
        {
            sleep(deadline - now);
            now = clock();
        }
    }

    /// <summary>Blocks the thread for at least durationNs nanoseconds.</summary>
    public static void SleepFor(long durationNs) =>
        SleepLoop(durationNs, NowNs, ns => Thread.Sleep(ToMilliseconds(ns)));

    /// <summary>Completes after at least durationNs nanoseconds. The thread is free in the meantime.</summary>
    public static async Task SleepForAsync(long durationNs, CancellationToken cancel = default)
    {
        long now = NowNs();
        long deadline = now + durationNs;
        while (now < deadline)
        {
            await Task.Delay(ToMilliseconds(deadline - now), cancel).ConfigureAwait(false);
            now = NowNs();
        }
    }

    /// <summary>Runs SleepLoop on a fake clock and returns the durations it asks for.</summary>
    public static long[] SleepRequests(long durationNs, long startNs, long[] readings)
    {
        var times = new List<long> { startNs };
        times.AddRange(readings);
        int next = 0;
        var requests = new List<long>();
        SleepLoop(durationNs, () => times[next++], requests.Add);
        return requests.ToArray();
    }

    /// <summary>
    /// Rounds ns up to whole milliseconds, because Thread.Sleep and Task.Delay take milliseconds,
    /// and cuts the result to int.MaxValue. A value of -1 would mean Timeout.Infinite.
    /// </summary>
    private static int ToMilliseconds(long ns)
    {
        long ms = ns / 1_000_000 + (ns % 1_000_000 > 0 ? 1 : 0);
        return (int)Math.Min(ms, int.MaxValue);
    }

    /// <summary>Reads the monotonic clock of Stopwatch in nanoseconds.</summary>
    private static long NowNs() =>
        (long)((Int128)Stopwatch.GetTimestamp() * 1_000_000_000 / Stopwatch.Frequency);
}
SleepTests.cs 65 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

using System.Diagnostics;
using System.Threading.Tasks;
using Xunit;

public sealed class SleepTests
{
    public static TheoryData<string, long, long, long[], long[]> Cases => new()
    {
        { "one-call", 1000000L, 0L, new long[] { 1000000L }, new long[] { 1000000L } },
        { "woke-late", 1000000L, 0L, new long[] { 1080000L }, new long[] { 1000000L } },
        { "woke-early", 1000000L, 0L, new long[] { 600000L, 1000000L }, new long[] { 1000000L, 400000L } },
        { "one-second", 1000000000L, 5000000000L, new long[] { 6000050000L }, new long[] { 1000000000L } },
        { "zero", 0L, 0L, new long[] { }, new long[] { } },
        { "negative", -5000000L, 0L, new long[] { }, new long[] { } },
        { "most-negative", -4611686018427387904L, 0L, new long[] { }, new long[] { } },
        { "several-early-wakes", 10000000L, 0L, new long[] { 2000000L, 5000000L, 9999999L, 10000000L }, new long[] { 10000000L, 8000000L, 5000000L, 1L } },
        { "no-progress", 1000000L, 0L, new long[] { 0L, 1000000L }, new long[] { 1000000L, 1000000L } },
        { "exact-deadline", 3000000L, 100L, new long[] { 3000100L }, new long[] { 3000000L } },
        { "one-ns-short", 3000000L, 0L, new long[] { 2999999L, 3000000L }, new long[] { 3000000L, 1L } },
        { "extra-readings", 1000000L, 0L, new long[] { 1000000L, 5000000L }, new long[] { 1000000L } },
        { "negative-origin", 2000000000L, -5000000000L, new long[] { -4000000000L, -3000000000L }, new long[] { 2000000000L, 1000000000L } },
        { "origin-after-100-days", 1500000L, 8640000000000000L, new long[] { 8640000001000000L, 8640000001500000L }, new long[] { 1500000L, 500000L } },
        { "one-nanosecond", 1L, 0L, new long[] { 1000000L }, new long[] { 1L } },
        { "sub-millisecond", 1500000L, 0L, new long[] { 1000000L, 1500000L }, new long[] { 1500000L, 500000L } },
        { "one-hour", 3600000000000L, 0L, new long[] { 3600000000000L }, new long[] { 3600000000000L } },
        { "thirty-days", 2592000000000000L, 0L, new long[] { 2147483647000000L, 2592000000000000L }, new long[] { 2592000000000000L, 444516353000000L } },
    };

    [Theory]
    [MemberData(nameof(Cases))]
    public void SleepRequests(string name, long durationNs, long startNs, long[] readings, long[] want)
    {
        Assert.True(name.Length > 0);
        Assert.Equal(want, Sleep.SleepRequests(durationNs, startNs, readings));
    }

    [Fact]
    public void SleepForWaitsAtLeastTheDuration()
    {
        var watch = Stopwatch.StartNew();
        Sleep.SleepFor(20_000_000);
        Assert.True(watch.Elapsed.Ticks >= 200_000);
    }

    [Theory]
    [InlineData(0L)]
    [InlineData(-5_000_000L)]
    public void SleepForReturnsAtOnce(long durationNs)
    {
        var watch = Stopwatch.StartNew();
        Sleep.SleepFor(durationNs);
        Assert.True(watch.ElapsedMilliseconds < 1000);
    }

    [Fact]
    public async Task TwoSleepsAtTheSameTimeTakeTheTimeOfOne()
    {
        var watch = Stopwatch.StartNew();
        await Task.WhenAll(Sleep.SleepForAsync(100_000_000), Sleep.SleepForAsync(100_000_000));
        Assert.InRange(watch.Elapsed.Ticks, 1_000_000, 1_999_999);
    }
}
sleep.jsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

import { hrtime } from "node:process";
import { setTimeout as delay } from "node:timers/promises";

/** The largest delay of a Node.js timer, in milliseconds. */
const MAX_DELAY_MS = 2147483647n;

/**
 * Sleeps until clock() reaches the deadline. A sleep that ends early is
 * followed by a sleep for the rest of the time.
 * @param {bigint} durationNs
 * @param {() => bigint} clock
 * @param {(ns: bigint) => Promise<void> | void} sleep
 * @returns {Promise<void>}
 */
export async function sleepLoop(durationNs, clock, sleep) {
  let now = clock();
  const deadline = now + durationNs;
  while (now < deadline) {
    await sleep(deadline - now);
    now = clock();
  }
}

/**
 * Waits on a timer for ns nanoseconds, rounded up to whole milliseconds and
 * cut to the largest delay of a timer.
 * @param {bigint} ns
 * @returns {Promise<void>}
 */
function timerSleep(ns) {
  let ms = (ns + 999_999n) / 1_000_000n;
  if (ms > MAX_DELAY_MS) ms = MAX_DELAY_MS;
  return delay(Number(ms));
}

/**
 * Resolves after at least durationNs nanoseconds. Other code runs in the
 * meantime.
 * @param {bigint} durationNs
 * @returns {Promise<void>}
 */
export function sleepFor(durationNs) {
  return sleepLoop(durationNs, hrtime.bigint, timerSleep);
}

/**
 * Runs sleepLoop on a fake clock and returns the durations it asks for.
 * @param {bigint} durationNs
 * @param {bigint} startNs
 * @param {bigint[]} readings
 * @returns {Promise<bigint[]>}
 */
export async function sleepRequests(durationNs, startNs, readings) {
  const times = [startNs, ...readings];
  let i = 0;
  const requests = [];
  await sleepLoop(durationNs, () => times[i++], (ns) => {
    requests.push(ns);
  });
  return requests;
}
sleep.test.js 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

import assert from "node:assert/strict";
import { hrtime } from "node:process";
import { test } from "node:test";

import { sleepFor, sleepRequests } from "./sleep.js";

const cases = [
  ["one-call", 1000000n, 0n, [1000000n], [1000000n]],
  ["woke-late", 1000000n, 0n, [1080000n], [1000000n]],
  ["woke-early", 1000000n, 0n, [600000n, 1000000n], [1000000n, 400000n]],
  ["one-second", 1000000000n, 5000000000n, [6000050000n], [1000000000n]],
  ["zero", 0n, 0n, [], []],
  ["negative", -5000000n, 0n, [], []],
  ["most-negative", -4611686018427387904n, 0n, [], []],
  ["several-early-wakes", 10000000n, 0n, [2000000n, 5000000n, 9999999n, 10000000n], [10000000n, 8000000n, 5000000n, 1n]],
  ["no-progress", 1000000n, 0n, [0n, 1000000n], [1000000n, 1000000n]],
  ["exact-deadline", 3000000n, 100n, [3000100n], [3000000n]],
  ["one-ns-short", 3000000n, 0n, [2999999n, 3000000n], [3000000n, 1n]],
  ["extra-readings", 1000000n, 0n, [1000000n, 5000000n], [1000000n]],
  ["negative-origin", 2000000000n, -5000000000n, [-4000000000n, -3000000000n], [2000000000n, 1000000000n]],
  ["origin-after-100-days", 1500000n, 8640000000000000n, [8640000001000000n, 8640000001500000n], [1500000n, 500000n]],
  ["one-nanosecond", 1n, 0n, [1000000n], [1n]],
  ["sub-millisecond", 1500000n, 0n, [1000000n, 1500000n], [1500000n, 500000n]],
  ["one-hour", 3600000000000n, 0n, [3600000000000n], [3600000000000n]],
  ["thirty-days", 2592000000000000n, 0n, [2147483647000000n, 2592000000000000n], [2592000000000000n, 444516353000000n]],
];

for (const [name, durationNs, startNs, readings, want] of cases) {
  test(name, async () => {
    assert.deepEqual(await sleepRequests(durationNs, startNs, readings), want);
  });
}

test("sleepFor waits at least the duration", async () => {
  const start = hrtime.bigint();
  await sleepFor(20_000_000n);
  assert.ok(hrtime.bigint() - start >= 20_000_000n);
});

test("sleepFor returns at once for zero and a negative duration", async () => {
  for (const ns of [0n, -5_000_000n]) {
    const start = hrtime.bigint();
    await sleepFor(ns);
    assert.ok(hrtime.bigint() - start < 1_000_000_000n);
  }
});

test("two sleeps at the same time take the time of one", async () => {
  const start = hrtime.bigint();
  await Promise.all([sleepFor(100_000_000n), sleepFor(100_000_000n)]);
  const elapsed = hrtime.bigint() - start;
  assert.ok(elapsed >= 100_000_000n && elapsed < 200_000_000n);
});
sleep.tsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

import { hrtime } from "node:process";
import { setTimeout as delay } from "node:timers/promises";

/** The largest delay of a Node.js timer, in milliseconds. */
const MAX_DELAY_MS = 2147483647n;

/**
 * Sleeps until clock() reaches the deadline. A sleep that ends early is
 * followed by a sleep for the rest of the time.
 */
export async function sleepLoop(
  durationNs: bigint,
  clock: () => bigint,
  sleep: (ns: bigint) => Promise<void> | void,
): Promise<void> {
  let now = clock();
  const deadline = now + durationNs;
  while (now < deadline) {
    await sleep(deadline - now);
    now = clock();
  }
}

/** Waits on a timer for ns nanoseconds, rounded up to whole milliseconds and cut to the largest delay of a timer. */
function timerSleep(ns: bigint): Promise<void> {
  let ms = (ns + 999_999n) / 1_000_000n;
  if (ms > MAX_DELAY_MS) ms = MAX_DELAY_MS;
  return delay(Number(ms));
}

/** Resolves after at least durationNs nanoseconds. Other code runs in the meantime. */
export function sleepFor(durationNs: bigint): Promise<void> {
  return sleepLoop(durationNs, hrtime.bigint, timerSleep);
}

/** Runs sleepLoop on a fake clock and returns the durations it asks for. */
export async function sleepRequests(durationNs: bigint, startNs: bigint, readings: bigint[]): Promise<bigint[]> {
  const times = [startNs, ...readings];
  let i = 0;
  const requests: bigint[] = [];
  await sleepLoop(
    durationNs,
    () => times[i++] as bigint,
    (ns) => {
      requests.push(ns);
    },
  );
  return requests;
}
sleep.test.ts 56 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

import assert from "node:assert/strict";
import { hrtime } from "node:process";
import { test } from "node:test";

import { sleepFor, sleepRequests } from "./sleep.ts";

const cases: [string, bigint, bigint, bigint[], bigint[]][] = [
  ["one-call", 1000000n, 0n, [1000000n], [1000000n]],
  ["woke-late", 1000000n, 0n, [1080000n], [1000000n]],
  ["woke-early", 1000000n, 0n, [600000n, 1000000n], [1000000n, 400000n]],
  ["one-second", 1000000000n, 5000000000n, [6000050000n], [1000000000n]],
  ["zero", 0n, 0n, [], []],
  ["negative", -5000000n, 0n, [], []],
  ["most-negative", -4611686018427387904n, 0n, [], []],
  ["several-early-wakes", 10000000n, 0n, [2000000n, 5000000n, 9999999n, 10000000n], [10000000n, 8000000n, 5000000n, 1n]],
  ["no-progress", 1000000n, 0n, [0n, 1000000n], [1000000n, 1000000n]],
  ["exact-deadline", 3000000n, 100n, [3000100n], [3000000n]],
  ["one-ns-short", 3000000n, 0n, [2999999n, 3000000n], [3000000n, 1n]],
  ["extra-readings", 1000000n, 0n, [1000000n, 5000000n], [1000000n]],
  ["negative-origin", 2000000000n, -5000000000n, [-4000000000n, -3000000000n], [2000000000n, 1000000000n]],
  ["origin-after-100-days", 1500000n, 8640000000000000n, [8640000001000000n, 8640000001500000n], [1500000n, 500000n]],
  ["one-nanosecond", 1n, 0n, [1000000n], [1n]],
  ["sub-millisecond", 1500000n, 0n, [1000000n, 1500000n], [1500000n, 500000n]],
  ["one-hour", 3600000000000n, 0n, [3600000000000n], [3600000000000n]],
  ["thirty-days", 2592000000000000n, 0n, [2147483647000000n, 2592000000000000n], [2592000000000000n, 444516353000000n]],
];

for (const [name, durationNs, startNs, readings, want] of cases) {
  test(name, async () => {
    assert.deepEqual(await sleepRequests(durationNs, startNs, readings), want);
  });
}

test("sleepFor waits at least the duration", async () => {
  const start = hrtime.bigint();
  await sleepFor(20_000_000n);
  assert.ok(hrtime.bigint() - start >= 20_000_000n);
});

test("sleepFor returns at once for zero and a negative duration", async () => {
  for (const ns of [0n, -5_000_000n]) {
    const start = hrtime.bigint();
    await sleepFor(ns);
    assert.ok(hrtime.bigint() - start < 1_000_000_000n);
  }
});

test("two sleeps at the same time take the time of one", async () => {
  const start = hrtime.bigint();
  await Promise.all([sleepFor(100_000_000n), sleepFor(100_000_000n)]);
  const elapsed = hrtime.bigint() - start;
  assert.ok(elapsed >= 100_000_000n && elapsed < 200_000_000n);
});
sleep.goI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

// Package sleep sleeps for a duration on a monotonic clock.
package sleep

import (
	"context"
	"time"
)

// SleepLoop sleeps until clock reaches the deadline. A sleep that ends early
// is followed by a sleep for the rest of the time.
func SleepLoop(durationNs int64, clock func() int64, sleep func(ns int64)) {
	now := clock()
	deadline := now + durationNs
	for now < deadline {
		sleep(deadline - now)
		now = clock()
	}
}

// SleepFor blocks the goroutine for at least d. time.Since uses the
// monotonic clock reading of base.
func SleepFor(d time.Duration) {
	base := time.Now()
	clock := func() int64 { return int64(time.Since(base)) }
	SleepLoop(int64(d), clock, func(ns int64) { time.Sleep(time.Duration(ns)) })
}

// SleepContext waits for d or until ctx is done, whichever comes first. It
// returns ctx.Err() if ctx is done first, and nil otherwise.
func SleepContext(ctx context.Context, d time.Duration) error {
	timer := time.NewTimer(d)
	defer timer.Stop()
	select {
	case <-timer.C:
		return nil
	case <-ctx.Done():
		return ctx.Err()
	}
}

// SleepRequests runs SleepLoop on a fake clock and returns the durations it
// asks for.
func SleepRequests(durationNs, startNs int64, readings []int64) []int64 {
	times := append([]int64{startNs}, readings...)
	next := 0
	requests := []int64{}
	SleepLoop(durationNs, func() int64 {
		t := times[next]
		next++
		return t
	}, func(ns int64) { requests = append(requests, ns) })
	return requests
}
sleep_test.go 78 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

package sleep

import (
	"context"
	"errors"
	"slices"
	"testing"
	"time"
)

var cases = []struct {
	name                string
	durationNs, startNs int64
	readings, want      []int64
}{
	{"one-call", 1000000, 0, []int64{1000000}, []int64{1000000}},
	{"woke-late", 1000000, 0, []int64{1080000}, []int64{1000000}},
	{"woke-early", 1000000, 0, []int64{600000, 1000000}, []int64{1000000, 400000}},
	{"one-second", 1000000000, 5000000000, []int64{6000050000}, []int64{1000000000}},
	{"zero", 0, 0, []int64{}, []int64{}},
	{"negative", -5000000, 0, []int64{}, []int64{}},
	{"most-negative", -4611686018427387904, 0, []int64{}, []int64{}},
	{"several-early-wakes", 10000000, 0, []int64{2000000, 5000000, 9999999, 10000000}, []int64{10000000, 8000000, 5000000, 1}},
	{"no-progress", 1000000, 0, []int64{0, 1000000}, []int64{1000000, 1000000}},
	{"exact-deadline", 3000000, 100, []int64{3000100}, []int64{3000000}},
	{"one-ns-short", 3000000, 0, []int64{2999999, 3000000}, []int64{3000000, 1}},
	{"extra-readings", 1000000, 0, []int64{1000000, 5000000}, []int64{1000000}},
	{"negative-origin", 2000000000, -5000000000, []int64{-4000000000, -3000000000}, []int64{2000000000, 1000000000}},
	{"origin-after-100-days", 1500000, 8640000000000000, []int64{8640000001000000, 8640000001500000}, []int64{1500000, 500000}},
	{"one-nanosecond", 1, 0, []int64{1000000}, []int64{1}},
	{"sub-millisecond", 1500000, 0, []int64{1000000, 1500000}, []int64{1500000, 500000}},
	{"one-hour", 3600000000000, 0, []int64{3600000000000}, []int64{3600000000000}},
	{"thirty-days", 2592000000000000, 0, []int64{2147483647000000, 2592000000000000}, []int64{2592000000000000, 444516353000000}},
}

func TestSleepRequests(t *testing.T) {
	for _, c := range cases {
		t.Run(c.name, func(t *testing.T) {
			if got := SleepRequests(c.durationNs, c.startNs, c.readings); !slices.Equal(got, c.want) {
				t.Errorf("SleepRequests(%d, %d, %v) = %v, want %v", c.durationNs, c.startNs, c.readings, got, c.want)
			}
		})
	}
}

func TestSleepForWaitsAtLeastTheDuration(t *testing.T) {
	start := time.Now()
	SleepFor(20 * time.Millisecond)
	if e := time.Since(start); e < 20*time.Millisecond {
		t.Errorf("SleepFor(20ms) took %v", e)
	}
}

func TestSleepForReturnsAtOnce(t *testing.T) {
	for _, d := range []time.Duration{0, -5 * time.Millisecond} {
		start := time.Now()
		SleepFor(d)
		if e := time.Since(start); e >= time.Second {
			t.Errorf("SleepFor(%v) took %v", d, e)
		}
	}
}

func TestSleepContextStopsWhenCanceled(t *testing.T) {
	ctx, cancel := context.WithTimeout(context.Background(), 20*time.Millisecond)
	defer cancel()
	start := time.Now()
	err := SleepContext(ctx, time.Hour)
	if !errors.Is(err, context.DeadlineExceeded) || time.Since(start) >= time.Second {
		t.Errorf("SleepContext = %v after %v", err, time.Since(start))
	}
	if err := SleepContext(context.Background(), time.Millisecond); err != nil {
		t.Errorf("SleepContext(1ms) = %v", err)
	}
}
sleep.rsI0RawGitHub
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

//! Sleeps for a duration on a monotonic clock.

use std::time::{Duration, Instant};

/// Sleeps until `clock` reaches the deadline. A sleep that ends early is
/// followed by a sleep for the rest of the time.
pub fn sleep_loop(duration_ns: i64, mut clock: impl FnMut() -> i64, mut sleep: impl FnMut(i64)) {
    let mut now = clock();
    let deadline = now + duration_ns;
    while now < deadline {
        sleep(deadline - now);
        now = clock();
    }
}

/// Blocks the thread for at least `duration_ns` nanoseconds. `Instant` is
/// monotonic.
pub fn sleep_for(duration_ns: i64) {
    let base = Instant::now();
    let clock = || i64::try_from(base.elapsed().as_nanos()).unwrap_or(i64::MAX);
    sleep_loop(duration_ns, clock, |ns| {
        std::thread::sleep(Duration::from_nanos(ns.unsigned_abs()));
    });
}

/// Runs `sleep_loop` on a fake clock and returns the durations it asks for.
#[must_use]
pub fn sleep_requests(duration_ns: i64, start_ns: i64, readings: &[i64]) -> Vec<i64> {
    let mut times = std::iter::once(start_ns).chain(readings.iter().copied());
    let mut requests = Vec::new();
    sleep_loop(
        duration_ns,
        || times.next().expect("a reading after each sleep"),
        |ns| requests.push(ns),
    );
    requests
}
tests/sleep_test.rs 52 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/sleep-for-a-duration/.

use std::time::{Duration, Instant};

use algo_sleep_for_a_duration::{sleep_for, sleep_requests};

type Case = (&'static str, i64, i64, &'static [i64], &'static [i64]);

const CASES: &[Case] = &[
    ("one-call", 1000000, 0, &[1000000], &[1000000]),
    ("woke-late", 1000000, 0, &[1080000], &[1000000]),
    ("woke-early", 1000000, 0, &[600000, 1000000], &[1000000, 400000]),
    ("one-second", 1000000000, 5000000000, &[6000050000], &[1000000000]),
    ("zero", 0, 0, &[], &[]),
    ("negative", -5000000, 0, &[], &[]),
    ("most-negative", -4611686018427387904, 0, &[], &[]),
    ("several-early-wakes", 10000000, 0, &[2000000, 5000000, 9999999, 10000000], &[10000000, 8000000, 5000000, 1]),
    ("no-progress", 1000000, 0, &[0, 1000000], &[1000000, 1000000]),
    ("exact-deadline", 3000000, 100, &[3000100], &[3000000]),
    ("one-ns-short", 3000000, 0, &[2999999, 3000000], &[3000000, 1]),
    ("extra-readings", 1000000, 0, &[1000000, 5000000], &[1000000]),
    ("negative-origin", 2000000000, -5000000000, &[-4000000000, -3000000000], &[2000000000, 1000000000]),
    ("origin-after-100-days", 1500000, 8640000000000000, &[8640000001000000, 8640000001500000], &[1500000, 500000]),
    ("one-nanosecond", 1, 0, &[1000000], &[1]),
    ("sub-millisecond", 1500000, 0, &[1000000, 1500000], &[1500000, 500000]),
    ("one-hour", 3600000000000, 0, &[3600000000000], &[3600000000000]),
    ("thirty-days", 2592000000000000, 0, &[2147483647000000, 2592000000000000], &[2592000000000000, 444516353000000]),
];

#[test]
fn requests() {
    for &(name, duration_ns, start_ns, readings, want) in CASES {
        assert_eq!(sleep_requests(duration_ns, start_ns, readings), want, "{name}");
    }
}

#[test]
fn sleep_for_waits_at_least_the_duration() {
    let start = Instant::now();
    sleep_for(20_000_000);
    assert!(start.elapsed() >= Duration::from_millis(20));
}

#[test]
fn sleep_for_returns_at_once() {
    for ns in [0, -5_000_000] {
        let start = Instant::now();
        sleep_for(ns);
        assert!(start.elapsed() < Duration::from_secs(1));
    }
}
sleep.shI0RawGitHub
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sleep-for-a-duration/.

# sleep_ns NS: one call of sleep(1) for NS nanoseconds, written as seconds
# with nine decimal places. GNU sleep takes a number that is not an integer.
sleep_ns() {
  local ns=$1
  sleep "$(printf '%d.%09d' "$((ns / 1000000000))" "$((ns % 1000000000))")"
}

# sleep_requests DURATION_NS START_NS READING...: runs the loop of the
# contract on a fake clock that gives START_NS and then each READING, and
# prints the durations that the loop asks for, with one space between them.
sleep_requests() {
  local now=$2 deadline=$(($2 + $1)) requests=()
  shift 2
  while ((now < deadline)); do
    requests+=("$((deadline - now))")
    now=$1
    shift
  done
  echo "${requests[*]}"
}

# sleep_for_ns NS: sleeps for at least NS nanoseconds. Bash has no monotonic
# clock, so the function makes one call of sleep. A negative or zero NS
# returns at once.
sleep_for_ns() {
  local ns=$1
  if ((ns > 0)); then
    sleep_ns "$ns"
  fi
}
test_sleep.bats 42 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/sleep-for-a-duration/.

setup() {
  source "$BATS_TEST_DIRNAME/sleep.sh"
}

@test "one-call" { run sleep_requests 1000000 0 1000000; [ "$status" -eq 0 ]; [ "$output" = "1000000" ]; }
@test "woke-late" { run sleep_requests 1000000 0 1080000; [ "$status" -eq 0 ]; [ "$output" = "1000000" ]; }
@test "woke-early" { run sleep_requests 1000000 0 600000 1000000; [ "$status" -eq 0 ]; [ "$output" = "1000000 400000" ]; }
@test "one-second" { run sleep_requests 1000000000 5000000000 6000050000; [ "$status" -eq 0 ]; [ "$output" = "1000000000" ]; }
@test "zero" { run sleep_requests 0 0; [ "$status" -eq 0 ]; [ "$output" = "" ]; }
@test "negative" { run sleep_requests -5000000 0; [ "$status" -eq 0 ]; [ "$output" = "" ]; }
@test "most-negative" { run sleep_requests -4611686018427387904 0; [ "$status" -eq 0 ]; [ "$output" = "" ]; }
@test "several-early-wakes" { run sleep_requests 10000000 0 2000000 5000000 9999999 10000000; [ "$status" -eq 0 ]; [ "$output" = "10000000 8000000 5000000 1" ]; }
@test "no-progress" { run sleep_requests 1000000 0 0 1000000; [ "$status" -eq 0 ]; [ "$output" = "1000000 1000000" ]; }
@test "exact-deadline" { run sleep_requests 3000000 100 3000100; [ "$status" -eq 0 ]; [ "$output" = "3000000" ]; }
@test "one-ns-short" { run sleep_requests 3000000 0 2999999 3000000; [ "$status" -eq 0 ]; [ "$output" = "3000000 1" ]; }
@test "extra-readings" { run sleep_requests 1000000 0 1000000 5000000; [ "$status" -eq 0 ]; [ "$output" = "1000000" ]; }
@test "negative-origin" { run sleep_requests 2000000000 -5000000000 -4000000000 -3000000000; [ "$status" -eq 0 ]; [ "$output" = "2000000000 1000000000" ]; }
@test "origin-after-100-days" { run sleep_requests 1500000 8640000000000000 8640000001000000 8640000001500000; [ "$status" -eq 0 ]; [ "$output" = "1500000 500000" ]; }
@test "one-nanosecond" { run sleep_requests 1 0 1000000; [ "$status" -eq 0 ]; [ "$output" = "1" ]; }
@test "sub-millisecond" { run sleep_requests 1500000 0 1000000 1500000; [ "$status" -eq 0 ]; [ "$output" = "1500000 500000" ]; }
@test "one-hour" { run sleep_requests 3600000000000 0 3600000000000; [ "$status" -eq 0 ]; [ "$output" = "3600000000000" ]; }
@test "thirty-days" { run sleep_requests 2592000000000000 0 2147483647000000 2592000000000000; [ "$status" -eq 0 ]; [ "$output" = "2592000000000000 444516353000000" ]; }

@test "sleep_for_ns waits at least the duration" {
  local start=$EPOCHREALTIME
  sleep_for_ns 20000000
  local end=$EPOCHREALTIME
  # EPOCHREALTIME has six decimal places, so the digits without the point are microseconds.
  (( ${end/[.,]/} - ${start/[.,]/} >= 20000 ))
}

@test "sleep_for_ns returns at once for zero and a negative duration" {
  local start=$EPOCHREALTIME
  sleep_for_ns 0
  sleep_for_ns -5000000
  local end=$EPOCHREALTIME
  (( ${end/[.,]/} - ${start/[.,]/} < 1000000 ))
}

References

  1. The Python Standard Library, time, time.sleep
  2. The Python Standard Library, Coroutines and Tasks, Sleeping
  3. Node.js documentation, Timers, setInterval and setTimeout; Timers Promises API
  4. MDN, setTimeout() global function, delay; Maximum delay value
  5. Java SE 21 API, java.lang.Thread, sleep(long millis)
  6. Java SE 21 API, java.util.concurrent.TimeUnit, sleep(long timeout)
  7. Java SE 21 API, java.lang.System, nanoTime()
  8. .NET API reference, Thread.Sleep, Sleep(Int32), Exceptions and Remarks
  9. .NET API reference, Task.Delay, Delay(Int32), Exceptions and Remarks
  10. Go standard library, time, func Sleep
  11. The Rust Standard Library, std::thread::sleep, the description and Platform-specific behavior
  12. Linux manual page, nanosleep(2), DESCRIPTION and NOTES
  13. Linux manual page, clock_nanosleep(2), DESCRIPTION
  14. cppreference.com, std::this_thread::sleep_for, the description of the function
  15. cppreference.com, std::this_thread::sleep_until, the description of the function
  16. Linux manual page, sleep(1), DESCRIPTION

About this page

The build computes these levels from the evidence in the repository. Each row says what the next level needs. Read what the levels mean.

LadderLevelWhat the next level needs
Human proofH0 no proof
  • add a proof in proofs/ (06.5)
LeanL0 no Lean part
  • name a Lean module in the lean field (07)
Code (bash)I0 not checked yet
  • the tests did not run in this build
Code (c)I0 not checked yet
  • the tests did not run in this build
Code (cpp)I0 not checked yet
  • the tests did not run in this build
Code (csharp)I0 not checked yet
  • the tests did not run in this build
Code (go)I0 not checked yet
  • the tests did not run in this build
Code (java)I0 not checked yet
  • the tests did not run in this build
Code (javascript)I0 not checked yet
  • the tests did not run in this build
Code (python)I0 not checked yet
  • the tests did not run in this build
Code (rust)I0 not checked yet
  • the tests did not run in this build
Code (typescript)I0 not checked yet
  • the tests did not run in this build
VisualV0 none
  • add viz/scene.ts or a figure (10)
WritingW3 standard
  • a history with a source