Alpha.16 · standard library

Time

Read a monotonic clock, construct exact durations and wait without blocking an async task.

These pages describe alpha.16. Host I/O requires the native toolchain; browser capabilities are limited. Browse the stdlib guides.

All standard library modules

Read a monotonic clock, construct exact durations and wait without blocking an async task.

Import

import stdlib/time as time

For an async function, select the async module instead:

import stdlib/time/async as time

Await effectful operations. In the signatures below, an ordinary effectful function becomes async under the async import; parameter and result types stay the same. Pure functions and value methods remain ordinary calls. The two imports share their value and error types.

now()

now(): Result[Instant,ClockError]

Parameters

None.

Returns: Result[Instant,ClockError]. Ok contains the current monotonic instant.

Use await time.now() with the async import. A clock read is impure, even though it completes in the current task turn. Instants from the same invocation share a clock domain; consecutive readings may be equal. An instant is not a calendar timestamp and must not be persisted for comparison with another invocation.

Errors: ClockUnavailable if the host cannot supply the monotonic clock.

sleep()

sleep(duration: Duration): Result[Unit,SleepError]

Parameters

  • duration: Duration — a wait from zero through 365 days.

Returns: Result[Unit,SleepError]. Ok(()) means the wait completed.

The ordinary form blocks. await time.sleep(duration) suspends the current task, allowing other tasks to progress. Zero completes immediately. Cancellation discards the async timer; it does not produce a normal successful return.

Errors: Negative durations produce NegativeDuration; waits beyond the host range produce DurationTooLarge. Timer, resource or host failures remain errors.

seconds()

pure seconds(value: Int): Duration

Parameters

  • value: Int — a signed number of seconds.

Returns: Duration, exactly representing the supplied value.

Pure. Negative durations are valid values, though APIs such as sleep reject them.

milliseconds()

pure milliseconds(value: Int): Duration

Parameters

  • value: Int — a signed number of milliseconds.

Returns: Duration, exactly representing the supplied value.

Pure. Negative durations are valid values, though APIs such as sleep reject them.

nanoseconds()

pure nanoseconds(value: Int): Duration

Parameters

  • value: Int — a signed number of nanoseconds.

Returns: Duration, exactly representing the supplied value.

Pure. Negative durations are valid values, though APIs such as sleep reject them.

from_fractional_seconds()

pure from_fractional_seconds(value: Rat): Result[Duration,DurationError]

Parameters

  • value: Rat — an exact number of seconds.

Returns: Result[Duration,DurationError].

Pure. Conversion requires an exact whole number of nanoseconds. No rounding is performed.

Errors: FractionalNanosecond when the input cannot be represented exactly.

Instant and Duration

These value methods are pure.

Instant.difference()

pure difference(start: Instant): Duration

Parameters

  • start: Instant: an instant from the same invocation.

Returns: Duration, this instant minus start, including a negative result when this instant is earlier.

Duration.as_nanoseconds()

pure as_nanoseconds(): Int

Parameters

None.

Returns: Int, the exact signed number of nanoseconds.

Duration.as_seconds()

pure as_seconds(): Rat

Parameters

None.

Returns: Rat, the exact signed number of seconds, without rounding.

Duration.add()

pure add(right: Duration): Duration

Parameters

  • right: Duration: the duration to add.

Returns: Duration, the exact sum.

Duration.subtract()

pure subtract(right: Duration): Duration

Parameters

  • right: Duration: the duration to subtract.

Returns: Duration, this duration minus right.

Duration.scale()

pure scale(factor: Int): Duration

Parameters

  • factor: Int: a signed multiplier.

Returns: Duration, this duration multiplied exactly by factor.

Duration.is_less_than()

pure is_less_than(right: Duration): Bool

Parameters

  • right: Duration: the duration to compare.

Returns: Bool, true when this duration is smaller than right.

Duration.divide()

pure divide(divisor: Int): Result[Duration,DurationError]

Parameters

  • divisor: Int: a nonzero signed divisor.

Returns: Result[Duration,DurationError]. Ok contains the exact quotient.

Errors: ZeroDurationDivisor for zero; FractionalNanosecond when the quotient cannot be represented as whole nanoseconds. No rounding is performed.

Duration.ratio()

pure ratio(right: Duration): Result[Rat,DurationError]

Parameters

  • right: Duration: a nonzero duration.

Returns: Result[Rat,DurationError]. Ok contains this duration divided by right as an exact rational number.

Errors: ZeroDurationDivisor when right is zero.

DurationError

DurationError has FractionalNanosecond and ZeroDurationDivisor. Compatibility factories from_nanoseconds and from_seconds retain the parameter and result types and behaviour of nanoseconds and from_fractional_seconds, respectively.

SleepError

record SleepError { duration: Duration, kind: SleepErrorKind, native: HostError }

duration is the requested wait. Use problem.kind for control flow and render for a human-readable explanation. The native field preserves the original failure. Host-backed native errors contain operation: Str, code: Str and native_code: Nat; a zero native number means no host error number was supplied.

enum SleepErrorKind { NegativeDuration, DurationTooLarge, TimerFailure, UnsupportedHost, OtherFailure }

SleepError.render()

pure render(): Str

Parameters

None.

Returns: Str, a human-readable explanation of this error, including the available operation and failure details.

Pure. Use the structured error fields for control flow; the wording is diagnostic text and must not be parsed.

Example

Read the complete timing program, including clock failures and the difference between two instants.

Complete example: async timing

import stdlib/time/async as time
import stdlib/console/async as console
import stdlib/host/async as host

async measure_pause(): Result[Bool,Str] {
  match await time.now() {
    Error(clock_error) => Error("The monotonic clock is unavailable."),
    Ok(start) => match await time.sleep(time.milliseconds(1)) {
      Error(problem) => Error(problem.render()),
      Ok(slept) => match await time.now() {
        Error(second_clock_error) => Error("The monotonic clock is unavailable."),
        Ok(end) => Ok(!end.is_before(start))
      }
    }
  }
}

async main(): Unit {
  match await measure_pause() {
    Error(message) => {
      reported = await console.write_error_line(message)
      await host.exit(1)
    },
    Ok(monotonic) => match await console.write_line("Clock did not move backwards: ${monotonic}") {
      Error(write_error) => await host.exit(1), Ok(written) => ()
    }
  }
}

Implementation: view source on GitHub.

Keep exploring

Explore Panackelty.