Standard Library: Time
The time module provides precision timing, async sleep, wall-clock millis,
and an N-iteration benchmark helper.
Importing
Section titled “Importing”use std::core::timeAll time functions live under the time namespace when imported as a module.
Nothing is injected into the global scope.
Instant
Section titled “Instant”time::now() returns an Instant representing a point on the monotonic clock.
Monotonic means it always moves forward — it is unaffected by wall-clock
adjustments like daylight savings or NTP corrections. This makes it the right
tool for measuring elapsed time.
let start = time::now()
// ... do some work ...let data = load_csv("records.csv")
let ms = start.elapsed()print(f"Loaded in {ms}ms")elapsed() returns the number of milliseconds since the instant was created.
Stopwatch Alias
Section titled “Stopwatch Alias”time::stopwatch() is currently an alias for time::now() — it returns an
Instant. The richer lap/stop API is on the roadmap but not yet implemented.
let sw = time::stopwatch()// ... do work ...let elapsed_ms = sw.elapsed()Instant API
Section titled “Instant API”| Method | Returns | Description |
|---|---|---|
time::now() | Instant | Current monotonic timestamp |
time::stopwatch() | Instant | Alias for time::now() |
instant.elapsed() | number | Milliseconds since creation |
Wall-Clock Milliseconds
Section titled “Wall-Clock Milliseconds”time::millis() returns the current wall-clock time as milliseconds since the
Unix epoch. Unlike Instant, this is affected by system clock adjustments.
let ts = time::millis()print(f"Epoch ms: {ts}")time::sleep(ms) pauses execution for the given number of milliseconds. It is
async — the runtime yields to other tasks during the pause instead of blocking
the thread.
async fn poll_status(url: string) { loop { let resp = await fetch(url) if resp.status == "complete" { return resp.data } await time::sleep(1000) // wait 1 second before retrying }}Because sleep is async, it must be called with await inside an async
function or at the top level of a script.
For blocking sleep (no async runtime needed), use time::sleep_sync(ms):
time::sleep_sync(500) // block the thread for 500msSleep API
Section titled “Sleep API”| Function | Description |
|---|---|
time::sleep(ms) | Async sleep (must be await-ed) |
time::sleep_sync(ms) | Blocking sleep |
Polling with Backoff
Section titled “Polling with Backoff”A common pattern combines sleep with increasing delays:
async fn poll_with_backoff(url: string, max_retries: int) { let mut delay = 100 for i in range(max_retries) { let resp = await fetch(url) if resp.status == "complete" { return resp.data } await time::sleep(delay) delay = delay * 2 // exponential backoff } error("Timed out after {max_retries} retries")}Benchmark
Section titled “Benchmark”time::benchmark(callback, iterations) runs callback for the requested
number of iterations and returns aggregate timing statistics.
let report = time::benchmark(|| { load_csv("large_dataset.csv") .filter(|row| row.count > 100) .group("category") .aggregate({ total: sum(|row| row.count) })}, 100)
print(f"Total: {report.elapsed_ms}ms")print(f"Iterations: {report.iterations}")print(f"Avg: {report.avg_ms}ms")Benchmark Result
Section titled “Benchmark Result”| Field | Type | Description |
|---|---|---|
elapsed_ms | number | Total execution time in milliseconds |
iterations | int | Number of iterations performed |
avg_ms | number | Average time per iteration |
Comparing Implementations
Section titled “Comparing Implementations”let a = time::benchmark(|| { data.filter(|r| r.value > threshold).map(|r| r.value * r.weight)}, 1000)
let b = time::benchmark(|| { data.map(|r| if r.value > threshold { r.value * r.weight } else { 0 })}, 1000)
print(f"Filter+Map avg: {a.avg_ms}ms")print(f"Single pass avg: {b.avg_ms}ms")Practical Examples
Section titled “Practical Examples”Rate-Limited API Calls
Section titled “Rate-Limited API Calls”Use sleep to respect API rate limits while fetching paginated data:
async fn fetch_all_pages(base_url: string) { let mut pages = [] let mut page = 1
loop { let resp = await fetch(f"{base_url}?page={page}") pages = pages.concat(resp.data)
if resp.next_page == None { break } page = page + 1 await time::sleep(200) // 5 requests per second }
pages}