Time

Loft provides two time functions:

now() — milliseconds since the Unix epoch (wall-clock time). ticks() — microseconds elapsed since program start (monotonic clock).

Both return a 'long'.

Use 'now()' for timestamps, log entries, and date calculations. Use 'ticks()' for benchmarks and frame timing — it is unaffected by system clock changes or NTP adjustments.

fn main() {

Wall-clock time: now()

'now()' returns the current time as milliseconds since 1970-01-01T00:00:00 UTC. The value is always positive and grows over time.

  t = now();
  assert(t > 0l, "now() must be positive");

Two successive calls return non-decreasing values.

  t2 = now();
  assert(t2 >= t, "now() must be non-decreasing");

Elapsed time: ticks()

'ticks()' measures microseconds since the program started. It uses a monotonic clock so it never jumps backward.

  start = ticks();
  assert(start >= 0l, "ticks() must be non-negative");
  end = ticks();
  assert(end >= start, "ticks() must be monotonically non-decreasing");

Measuring elapsed time

Subtract two 'ticks()' values to get the duration in microseconds. Divide by 1000 to convert to milliseconds.

elapsed_us = end_ticks - start_ticks elapsed_ms = elapsed_us / 1000l

Example: measure how long a loop takes.

  t_before = ticks();
  sum = 0;
  for i in 0..1000 {
    sum += i
  }
  t_after = ticks();
  elapsed = t_after - t_before;
  assert(elapsed >= 0l, "elapsed time must be non-negative: {elapsed}");
  assert(sum == 499500, "loop produced wrong sum: {sum}");

Common patterns

Timestamp a log entry (seconds since epoch): seconds = now() / 1000l

Seed the random number generator with the current time: rand_seed(now() as integer)

Simple stopwatch: start = ticks() ... do work ... log_info("Done in {(ticks() - start) / 1000l} ms")

}