Skip to content

Standard Library: Time

The time module provides precision timing, async sleep, wall-clock millis, and an N-iteration benchmark helper.

use std::core::time

All time functions live under the time namespace when imported as a module. Nothing is injected into the global scope.

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.

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()
MethodReturnsDescription
time::now()InstantCurrent monotonic timestamp
time::stopwatch()InstantAlias for time::now()
instant.elapsed()numberMilliseconds since creation

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 500ms
FunctionDescription
time::sleep(ms)Async sleep (must be await-ed)
time::sleep_sync(ms)Blocking sleep

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")
}

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")
FieldTypeDescription
elapsed_msnumberTotal execution time in milliseconds
iterationsintNumber of iterations performed
avg_msnumberAverage time per iteration
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")

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
}
  • DateTime — wall-clock dates and calendar arithmetic
  • Asyncawait, join, async scope, and for await