Taskcore
Measure elapsed time
Also called time a function, measure how long code takes, use a monotonic clock, stopwatch, measure a duration.
Measure how long a piece of work takes with a monotonic clock, not the wall clock, and print the duration in milliseconds with integer arithmetic on nanoseconds.
- Evidence
- Code in 10 languages
Task
Measure how long a piece of work takes, and print the duration. Read a monotonic clock before and after the work, and subtract the two readings. Do not use the wall clock, because a person or a time service can set it forward or back while the work runs.
The real duration changes on each run, so the contract tests the arithmetic and the format. elapsed_ms(start_ns, end_ns) takes two readings of a monotonic clock in nanoseconds and returns the difference as M.UUU ms: the whole milliseconds, a dot, and three digits of microseconds. The part under one microsecond is dropped, not rounded. The readings can be negative, because the origin of a monotonic clock is arbitrary. They can be as large as a signed 64-bit integer allows.
Each solution also has measure(work, clock). It reads the clock, runs the work once, reads the clock again and returns the difference. Its tests give a fake clock with fixed readings, and they check the order of the calls. One more test uses the real clock and checks only that the result is not negative.
Solutions
Each solution keeps the readings as integer nanoseconds and uses integer division. A floating-point number of seconds loses nanoseconds when the reading is large (see the pitfalls).
- Python.
time.monotonic_ns()returns anint. The clock cannot go backwards, and updates of the system clock do not change it. Only the difference of two readings has a meaning. The documentation says to usemonotonic_ns()to avoid the precision loss offloat. - JavaScript and TypeScript (Node.js).
process.hrtime.bigint()returns abigintof nanoseconds. The time is relative to an arbitrary time in the past and is not related to the time of day. The division of twobigintvalues truncates.performance.now()returns anumberof milliseconds. The legacyprocess.hrtime()returns an array of seconds and nanoseconds. - Java.
System.nanoTime()returns alongof nanoseconds from an arbitrary origin, which can be in the future, so a reading can be negative. Only a difference has a meaning.String.formatgetsLocale.ROOT, becauseFormatterwrites the digits of the locale. - C#.
TimeProvider.System.GetTimestamp()returns a time stamp fromStopwatch, andGetElapsedTime(start, end)converts the difference to aTimeSpan. A test gives a subclass ofTimeProviderthat overridesGetTimestampandTimestampFrequency. - Go.
time.Now()returns aTimewith a wall clock reading and a monotonic clock reading.Subandtime.Sinceuse the monotonic readings when both times have one. The fake clock in the test returns times fromtime.Unix, which have no monotonic reading, soSubuses their wall readings. - Rust.
Instant::now()reads a monotonic clock. AnInstantis opaque, so the fake clock adds fixedDurationvalues to one realInstant.duration_sincereturns aDuration. - C.
clock_gettime(CLOCK_MONOTONIC, &ts)fills astruct timespec. POSIX requires each implementation to support this clock, andclock_settimecannot set it. The code putstv_secandtv_nsecinto oneint64_tof nanoseconds, so a subtraction needs no borrow between the two fields.measuretakes the clock as a function pointer. - C++.
std::chrono::steady_clockis monotonic and is not related to the wall clock.measuretakes the clock as a template parameter, and astatic_assertrejects a clock whoseis_steadyis false.high_resolution_clockcan be an alias ofsystem_clock, so do not use it to measure a duration. - Bash. In Bash 5.3,
BASH_MONOSECONDSexpands to a reading of the monotonic clock of the system. With no monotonic clock, it is the same asEPOCHSECONDS. Both give whole seconds, somonotonic_nsgives only multiples of 10^9.EPOCHREALTIMEhas microseconds, but it counts from the Unix epoch, so it is the wall clock.measuretakes the clock as a command. Shell arithmetic uses the largest fixed-width integers and does not check for overflow.
A real measurement prints a different number on each run. A program that must give the same output can print a check:
import time
def work():
return sum(range(100_000))
start = time.monotonic_ns()
work()
elapsed = time.monotonic_ns() - start
print("elapsed >= 0:", elapsed >= 0)
elapsed >= 0: True
Edge cases
The cases are in cases/basic.jsonl and cases/edge.jsonl.
zero: two equal readings give0.000 ms.under-one-microsecondandtruncate-not-round: 999 ns gives0.000 ms, and 1999999 ns gives1.999 ms. Rounding gives0.001 msand2.000 ms.leading-zero-in-fractionandexact-ms: 1005000 ns is1.005 ms, not1.5 ms. The format pads the microseconds to three digits.one-hour: 3.6 × 10^12 ns. A 32-bit integer cannot hold it.negative-readingsandacross-zero: the readings are below zero, or the zero is between them. The Java documentation says thatnanoTimecan be negative.beyond-2-pow-53: the start is 9007199254740993, which a 64-bit float cannot hold. The true difference is 1000999 ns. A float subtraction gives 1001000 ns, so the result is1.001 ms, not1.000 ms.near-int64-maxandnear-int64-min: readings at the ends of the signed 64-bit range. JavaScript needsbiginthere, and C needsint64_t.
Pitfalls
- A floating-point reading loses nanoseconds. A 64-bit float holds each integer up to 2^53 exactly, but not each integer above it. In JavaScript, keep the
bigintfromhrtime.bigint(), and do not convert it to anumberbefore the subtraction:
This code runs but gives a wrong answer on purpose.
const start = 9007199254740993n;
const end = 9007199255741992n;
console.log(end - start);
console.log(Number(end) - Number(start));
1000999n
1001000
- Compare a
nanoTimedifference, not two readings. The origin ofnanoTimeis arbitrary, so a reading can be near the end of the range oflong, and a sum can wrap to a negative value. The Java documentation says to writeSystem.nanoTime() - startTime >= timeoutNanos, notSystem.nanoTime() >= startTime + timeoutNanos:
This code runs but gives a wrong answer on purpose.
public class Main {
public static void main(String[] args) {
long startTime = Long.MAX_VALUE - 1_000;
long now = startTime + 2_000;
long timeoutNanos = 500;
System.out.println("now >= startTime + timeoutNanos: " + (now >= startTime + timeoutNanos));
System.out.println("now - startTime >= timeoutNanos: " + (now - startTime >= timeoutNanos));
}
}
now >= startTime + timeoutNanos: false
now - startTime >= timeoutNanos: true
- A Go
Timeloses its monotonic reading.t.Round(0)and the marshal methods drop it.time.Date,time.Parse,time.Unixand the unmarshal methods make times without it.Subon such a time uses the wall clock. Keep theTimefromtime.Now()in memory, and do not store it and read it back to measure.Stringshows the monotonic reading asm=±<value>:
This code runs but gives a wrong answer on purpose.
package main
import (
"fmt"
"strings"
"time"
)
func main() {
start := time.Now()
var restored time.Time
text, _ := start.MarshalText()
if err := restored.UnmarshalText(text); err != nil {
panic(err)
}
fmt.Println("start has m=:", strings.Contains(start.String(), "m="))
fmt.Println("restored has m=:", strings.Contains(restored.String(), "m="))
fmt.Println("Round(0) has m=:", strings.Contains(start.Round(0).String(), "m="))
}
start has m=: true
restored has m=: false
Round(0) has m=: false
clock()in C measures processor time.clockreturns the approximate processor time of the process, not the elapsed time. This program sleeps for 0.2 seconds. Useclock_gettime(CLOCK_MONOTONIC):
This code runs but gives a wrong answer on purpose.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <time.h>
static double seconds(struct timespec ts) {
return (double)ts.tv_sec + (double)ts.tv_nsec / 1e9;
}
int main(void) {
struct timespec start, end;
clock_t cpu_start = clock();
clock_gettime(CLOCK_MONOTONIC, &start);
nanosleep(&(struct timespec){.tv_nsec = 200000000}, nullptr);
clock_gettime(CLOCK_MONOTONIC, &end);
double cpu = (double)(clock() - cpu_start) / CLOCKS_PER_SEC;
printf("clock() < 0.1 s: %s\n", cpu < 0.1 ? "true" : "false");
printf("CLOCK_MONOTONIC >= 0.2 s: %s\n", seconds(end) - seconds(start) >= 0.2 ? "true" : "false");
}
clock() < 0.1 s: true
CLOCK_MONOTONIC >= 0.2 s: true
duration_sincehides a swapped order. In Rust,earlier.duration_since(later)returns zero, not an error. Usechecked_duration_sincewhen the order is not certain:
This code runs but gives a wrong answer on purpose.
use std::time::{Duration, Instant};
fn main() {
let start = Instant::now();
let end = start + Duration::from_millis(5);
println!("{:?}", end.duration_since(start));
println!("{:?}", start.duration_since(end));
println!("{:?}", start.checked_duration_since(end));
}
5ms
0ns
None
- The wall clock can go back. Python
time.time(), JavaSystem.currentTimeMillis(), BashEPOCHREALTIMEand CCLOCK_REALTIMEgive the time of day. The Python documentation says thattime.time()can return a lower value than a previous call if the system clock is set back between the two calls. A duration from two such readings can be wrong or negative. IfStopwatchin .NET has no high-resolution counter, its time stamp isDateTime.UtcNow.Ticks, which also comes from the wall clock.
Related tasks
- Parse and format a date: read and write the time of day, which comes from the wall clock.
- Generate random numbers: another task whose output changes on each run, and how to test it.
- Parse an integer: read a number of nanoseconds from text into a 64-bit integer.
Code
The build runs the native tests of each language in a pinned toolchain.
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/measure-elapsed-time/.
import time
from collections.abc import Callable
def measure(work: Callable[[], object], clock: Callable[[], int] = time.monotonic_ns) -> int:
"""Run work once and return the time it took, in nanoseconds of clock."""
# monotonic_ns is not changed by updates of the system clock, and an int has no rounding.
start = clock()
work()
return clock() - start
def elapsed_ms(start_ns: int, end_ns: int) -> str:
"""Return end_ns - start_ns as "M.UUU ms", with the rest under one microsecond dropped."""
ns = end_ns - start_ns
return f"{ns // 1_000_000}.{ns // 1_000 % 1_000:03d} ms"
test_elapsed.py 53 lines
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/measure-elapsed-time/.
import pytest
from elapsed import elapsed_ms, measure
CASES = [
("one-and-a-half-ms", 1000000000, 1001500000, "1.500 ms"),
("seconds", 0, 2345678901, "2345.678 ms"),
("under-one-ms", 50000, 750000, "0.700 ms"),
("zero", 123456789, 123456789, "0.000 ms"),
("under-one-microsecond", 0, 999, "0.000 ms"),
("truncate-not-round", 0, 1999999, "1.999 ms"),
("leading-zero-in-fraction", 0, 1005000, "1.005 ms"),
("exact-ms", 0, 7000000, "7.000 ms"),
("one-hour", 0, 3600000000000, "3600000.000 ms"),
("negative-readings", -5000000, -3500000, "1.500 ms"),
("across-zero", -1000000, 500000, "1.500 ms"),
("beyond-2-pow-53", 9007199254740993, 9007199255741992, "1.000 ms"),
("near-int64-max", 9223372035854775807, 9223372036854775807, "1000.000 ms"),
("near-int64-min", -9223372036854775808, -9223372035854775808, "1000.000 ms"),
]
@pytest.mark.parametrize(("name", "start_ns", "end_ns", "want"), CASES, ids=[c[0] for c in CASES])
def test_elapsed_ms(name, start_ns, end_ns, want):
assert elapsed_ms(start_ns, end_ns) == want
def test_float_seconds_lose_the_difference():
# The case beyond-2-pow-53 gives another answer with float arithmetic.
start, end = 9_007_199_254_740_993, 9_007_199_255_741_992
assert end - start == 1_000_999
assert int(float(end) - float(start)) == 1_001_000
def test_measure_with_a_fake_clock():
calls = []
readings = iter([5_000_000, 6_500_000])
def clock():
calls.append("clock")
return next(readings)
assert measure(lambda: calls.append("work"), clock) == 1_500_000
assert calls == ["clock", "work", "clock"]
def test_measure_with_the_monotonic_clock():
calls = []
assert measure(lambda: calls.append("work")) >= 0
assert calls == ["work"]
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
#include "elapsed.hpp"
#include <format>
std::string elapsed_ms(std::int64_t start_ns, std::int64_t end_ns) {
std::int64_t ns = end_ns - start_ns;
// Integer division truncates, and ns is not negative.
return std::format("{}.{:03} ms", ns / 1'000'000, ns / 1'000 % 1'000);
}
elapsed.hpp 25 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
#ifndef ELAPSED_HPP
#define ELAPSED_HPP
#include <chrono>
#include <cstdint>
#include <string>
#include <utility>
// Runs work once and returns the time it took on Clock. steady_clock is monotonic, and it is not related to the
// wall clock. A test can give another type with a static now().
template <typename Clock = std::chrono::steady_clock, typename Work>
typename Clock::duration measure(Work&& work) {
static_assert(Clock::is_steady, "measure needs a clock that does not go back");
auto start = Clock::now();
std::forward<Work>(work)();
return Clock::now() - start;
}
// Returns end_ns - start_ns as "M.UUU ms", with the rest under one microsecond dropped.
std::string elapsed_ms(std::int64_t start_ns, std::int64_t end_ns);
#endif
test_elapsed.cpp 85 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
#include <chrono>
#include <cstdint>
#include <cstdio>
#include <string>
#include <vector>
#include "elapsed.hpp"
namespace {
struct test_case {
const char* name;
std::int64_t start_ns, end_ns;
const char* want;
};
const test_case cases[] = {
{"one-and-a-half-ms", INT64_C(1000000000), INT64_C(1001500000), "1.500 ms"},
{"seconds", INT64_C(0), INT64_C(2345678901), "2345.678 ms"},
{"under-one-ms", INT64_C(50000), INT64_C(750000), "0.700 ms"},
{"zero", INT64_C(123456789), INT64_C(123456789), "0.000 ms"},
{"under-one-microsecond", INT64_C(0), INT64_C(999), "0.000 ms"},
{"truncate-not-round", INT64_C(0), INT64_C(1999999), "1.999 ms"},
{"leading-zero-in-fraction", INT64_C(0), INT64_C(1005000), "1.005 ms"},
{"exact-ms", INT64_C(0), INT64_C(7000000), "7.000 ms"},
{"one-hour", INT64_C(0), INT64_C(3600000000000), "3600000.000 ms"},
{"negative-readings", INT64_C(-5000000), INT64_C(-3500000), "1.500 ms"},
{"across-zero", INT64_C(-1000000), INT64_C(500000), "1.500 ms"},
{"beyond-2-pow-53", INT64_C(9007199254740993), INT64_C(9007199255741992), "1.000 ms"},
{"near-int64-max", INT64_C(9223372035854775807), INT64_C(9223372036854775807), "1000.000 ms"},
{"near-int64-min", INT64_MIN, INT64_C(-9223372035854775808), "1000.000 ms"},
};
std::string calls;
// A clock that returns fixed readings in order and logs each call.
struct fake_clock {
using rep = std::int64_t;
using period = std::nano;
using duration = std::chrono::nanoseconds;
using time_point = std::chrono::time_point<fake_clock>;
static constexpr bool is_steady = true;
static inline std::vector<rep> readings;
static time_point now() {
calls += "clock ";
rep r = readings.front();
readings.erase(readings.begin());
return time_point(duration(r));
}
};
} // namespace
int main() {
int failed = 0;
for (const test_case& c : cases) {
std::string got = elapsed_ms(c.start_ns, c.end_ns);
if (got != c.want) {
std::fprintf(stderr, "FAIL %s: got \"%s\"\n", c.name, got.c_str());
failed++;
}
}
fake_clock::readings = {5'000'000, 6'500'000};
auto got = measure<fake_clock>([] { calls += "work "; });
if (got != std::chrono::microseconds(1'500) || calls != "clock work clock ") {
std::fprintf(stderr, "FAIL fake clock: calls \"%s\"\n", calls.c_str());
failed++;
}
calls.clear();
if (measure([] { calls += "work "; }) < std::chrono::steady_clock::duration::zero() || calls != "work ") {
std::fprintf(stderr, "FAIL steady clock\n");
failed++;
}
if (failed > 0) {
return 1;
}
std::printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
import java.util.Locale;
import java.util.function.LongSupplier;
/** Measures the time that a piece of work takes. */
public final class Elapsed {
private Elapsed() {}
/** Runs work once and returns the time it took, in nanoseconds of System.nanoTime. */
public static long measure(Runnable work) {
// nanoTime is not related to the wall clock. Only a difference of two values has a meaning.
return measure(work, System::nanoTime);
}
/** Runs work once and returns the time it took, in nanoseconds of clock. */
public static long measure(Runnable work, LongSupplier clock) {
long start = clock.getAsLong();
work.run();
return clock.getAsLong() - start;
}
/** Returns endNs - startNs as "M.UUU ms", with the rest under one microsecond dropped. */
public static String elapsedMs(long startNs, long endNs) {
long ns = endNs - startNs;
// Locale.ROOT keeps the digits ASCII. Division of a long that is not negative truncates.
return String.format(Locale.ROOT, "%d.%03d ms", ns / 1_000_000, ns / 1_000 % 1_000);
}
}
ElapsedTest.java 61 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
import static org.junit.jupiter.api.Assertions.assertEquals;
import static org.junit.jupiter.api.Assertions.assertTrue;
import java.util.ArrayList;
import java.util.List;
import java.util.function.LongSupplier;
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 ElapsedTest {
static Stream<Arguments> cases() {
return Stream.of(
Arguments.of("one-and-a-half-ms", 1000000000L, 1001500000L, "1.500 ms"),
Arguments.of("seconds", 0L, 2345678901L, "2345.678 ms"),
Arguments.of("under-one-ms", 50000L, 750000L, "0.700 ms"),
Arguments.of("zero", 123456789L, 123456789L, "0.000 ms"),
Arguments.of("under-one-microsecond", 0L, 999L, "0.000 ms"),
Arguments.of("truncate-not-round", 0L, 1999999L, "1.999 ms"),
Arguments.of("leading-zero-in-fraction", 0L, 1005000L, "1.005 ms"),
Arguments.of("exact-ms", 0L, 7000000L, "7.000 ms"),
Arguments.of("one-hour", 0L, 3600000000000L, "3600000.000 ms"),
Arguments.of("negative-readings", -5000000L, -3500000L, "1.500 ms"),
Arguments.of("across-zero", -1000000L, 500000L, "1.500 ms"),
Arguments.of("beyond-2-pow-53", 9007199254740993L, 9007199255741992L, "1.000 ms"),
Arguments.of("near-int64-max", 9223372035854775807L, 9223372036854775807L, "1000.000 ms"),
Arguments.of("near-int64-min", Long.MIN_VALUE, -9223372035854775808L, "1000.000 ms")
);
}
@ParameterizedTest(name = "{0}")
@MethodSource("cases")
void elapsedMs(String name, long startNs, long endNs, String want) {
assertEquals(want, Elapsed.elapsedMs(startNs, endNs));
}
@Test
void measureWithAFakeClock() {
List<String> calls = new ArrayList<>();
long[] readings = {5_000_000L, 6_500_000L};
int[] next = {0};
LongSupplier clock = () -> {
calls.add("clock");
return readings[next[0]++];
};
assertEquals(1_500_000L, Elapsed.measure(() -> calls.add("work"), clock));
assertEquals(List.of("clock", "work", "clock"), calls);
}
@Test
void measureWithTheMonotonicClock() {
List<String> calls = new ArrayList<>();
assertTrue(Elapsed.measure(() -> calls.add("work")) >= 0);
assertEquals(List.of("work"), calls);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
#define _POSIX_C_SOURCE 200809L
#include "elapsed.h"
#include <inttypes.h>
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
int64_t monotonic_ns(void *ctx) {
(void)ctx;
struct timespec ts;
// POSIX requires each implementation to support CLOCK_MONOTONIC, so this call does not fail.
if (clock_gettime(CLOCK_MONOTONIC, &ts) != 0) {
abort();
}
// One int64_t holds the whole reading, so a subtraction needs no borrow from tv_sec.
return (int64_t)ts.tv_sec * 1000000000 + ts.tv_nsec;
}
int64_t measure(void (*work)(void *), void *work_ctx, elapsed_clock *clock, void *clock_ctx) {
int64_t start = clock(clock_ctx);
work(work_ctx);
return clock(clock_ctx) - start;
}
int elapsed_ms(int64_t start_ns, int64_t end_ns, char *buf, size_t size) {
int64_t ns = end_ns - start_ns;
// Integer division truncates, and ns is not negative.
return snprintf(buf, size, "%" PRId64 ".%03" PRId64 " ms", ns / 1000000, ns / 1000 % 1000);
}
elapsed.h 23 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
#ifndef ELAPSED_H
#define ELAPSED_H
#include <stddef.h>
#include <stdint.h>
// A clock returns a reading in nanoseconds. ctx is passed through.
typedef int64_t elapsed_clock(void *ctx);
// The real clock: CLOCK_MONOTONIC in nanoseconds. ctx is not used.
int64_t monotonic_ns(void *ctx);
// Runs work(work_ctx) once and returns the time it took, in nanoseconds of clock.
int64_t measure(void (*work)(void *), void *work_ctx, elapsed_clock *clock, void *clock_ctx);
// Writes end_ns - start_ns as "M.UUU ms" to buf, with the rest under one microsecond dropped.
// Returns the length of the text, as snprintf does. 32 bytes are always enough.
int elapsed_ms(int64_t start_ns, int64_t end_ns, char *buf, size_t size);
#endif
test_elapsed.c 81 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
#include "elapsed.h"
#include <stdio.h>
#include <string.h>
struct test_case {
const char *name;
int64_t start_ns, end_ns;
const char *want;
};
static const struct test_case cases[] = {
{"one-and-a-half-ms", INT64_C(1000000000), INT64_C(1001500000), "1.500 ms"},
{"seconds", INT64_C(0), INT64_C(2345678901), "2345.678 ms"},
{"under-one-ms", INT64_C(50000), INT64_C(750000), "0.700 ms"},
{"zero", INT64_C(123456789), INT64_C(123456789), "0.000 ms"},
{"under-one-microsecond", INT64_C(0), INT64_C(999), "0.000 ms"},
{"truncate-not-round", INT64_C(0), INT64_C(1999999), "1.999 ms"},
{"leading-zero-in-fraction", INT64_C(0), INT64_C(1005000), "1.005 ms"},
{"exact-ms", INT64_C(0), INT64_C(7000000), "7.000 ms"},
{"one-hour", INT64_C(0), INT64_C(3600000000000), "3600000.000 ms"},
{"negative-readings", INT64_C(-5000000), INT64_C(-3500000), "1.500 ms"},
{"across-zero", INT64_C(-1000000), INT64_C(500000), "1.500 ms"},
{"beyond-2-pow-53", INT64_C(9007199254740993), INT64_C(9007199255741992), "1.000 ms"},
{"near-int64-max", INT64_C(9223372035854775807), INT64_C(9223372036854775807), "1000.000 ms"},
{"near-int64-min", INT64_MIN, INT64_C(-9223372035854775808), "1000.000 ms"},
};
// The fake clock returns its readings in order and logs each call.
struct fake_clock {
const int64_t *readings;
size_t next;
char *log;
};
static int64_t fake_now(void *ctx) {
struct fake_clock *c = ctx;
strcat(c->log, "clock ");
return c->readings[c->next++];
}
static void log_work(void *ctx) {
strcat(ctx, "work ");
}
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];
char got[32];
elapsed_ms(c->start_ns, c->end_ns, got, sizeof got);
if (strcmp(got, c->want) != 0) {
fprintf(stderr, "FAIL %s: got \"%s\"\n", c->name, got);
failed++;
}
}
char log[64] = "";
const int64_t readings[] = {5000000, 6500000};
struct fake_clock fake = {readings, 0, log};
int64_t got = measure(log_work, log, fake_now, &fake);
if (got != 1500000 || strcmp(log, "clock work clock ") != 0) {
fprintf(stderr, "FAIL fake clock: got %lld, log \"%s\"\n", (long long)got, log);
failed++;
}
char real_log[64] = "";
if (measure(log_work, real_log, monotonic_ns, nullptr) < 0 || strcmp(real_log, "work ") != 0) {
fprintf(stderr, "FAIL monotonic clock\n");
failed++;
}
if (failed > 0) {
return 1;
}
printf("ok\n");
return 0;
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
using System.Globalization;
/// <summary>Measures the time that a piece of work takes.</summary>
public static class Elapsed
{
/// <summary>Runs work once and returns the time it took on the clock of time.</summary>
/// <remarks>TimeProvider.System uses the time stamp of Stopwatch. A test can give a fake TimeProvider.</remarks>
public static TimeSpan Measure(Action work, TimeProvider? time = null)
{
time ??= TimeProvider.System;
long start = time.GetTimestamp();
work();
return time.GetElapsedTime(start, time.GetTimestamp());
}
/// <summary>Returns endNs - startNs as "M.UUU ms", with the rest under one microsecond dropped.</summary>
public static string ElapsedMs(long startNs, long endNs)
{
long ns = endNs - startNs;
return string.Create(CultureInfo.InvariantCulture, $"{ns / 1_000_000}.{ns / 1_000 % 1_000:D3} ms");
}
}
ElapsedTests.cs 64 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
using Xunit;
public sealed class ElapsedTests
{
public static TheoryData<string, long, long, string> Cases => new()
{
{ "one-and-a-half-ms", 1000000000L, 1001500000L, "1.500 ms" },
{ "seconds", 0L, 2345678901L, "2345.678 ms" },
{ "under-one-ms", 50000L, 750000L, "0.700 ms" },
{ "zero", 123456789L, 123456789L, "0.000 ms" },
{ "under-one-microsecond", 0L, 999L, "0.000 ms" },
{ "truncate-not-round", 0L, 1999999L, "1.999 ms" },
{ "leading-zero-in-fraction", 0L, 1005000L, "1.005 ms" },
{ "exact-ms", 0L, 7000000L, "7.000 ms" },
{ "one-hour", 0L, 3600000000000L, "3600000.000 ms" },
{ "negative-readings", -5000000L, -3500000L, "1.500 ms" },
{ "across-zero", -1000000L, 500000L, "1.500 ms" },
{ "beyond-2-pow-53", 9007199254740993L, 9007199255741992L, "1.000 ms" },
{ "near-int64-max", 9223372035854775807L, 9223372036854775807L, "1000.000 ms" },
{ "near-int64-min", long.MinValue, -9223372035854775808L, "1000.000 ms" },
};
[Theory]
[MemberData(nameof(Cases))]
public void ElapsedMs(string name, long startNs, long endNs, string want)
{
Assert.False(string.IsNullOrEmpty(name));
Assert.Equal(want, Elapsed.ElapsedMs(startNs, endNs));
}
/// <summary>A clock that counts in nanoseconds and returns fixed readings.</summary>
private sealed class FakeClock(List<string> calls, params long[] readings) : TimeProvider
{
private int next;
public override long TimestampFrequency => 1_000_000_000;
public override long GetTimestamp()
{
calls.Add("clock");
return readings[next++];
}
}
[Fact]
public void MeasureWithAFakeClock()
{
var calls = new List<string>();
var clock = new FakeClock(calls, 5_000_000, 6_500_000);
Assert.Equal(TimeSpan.FromMilliseconds(1.5), Elapsed.Measure(() => calls.Add("work"), clock));
Assert.Equal(["clock", "work", "clock"], calls);
}
[Fact]
public void MeasureWithTheMonotonicClock()
{
var calls = new List<string>();
Assert.True(Elapsed.Measure(() => calls.Add("work")) >= TimeSpan.Zero);
Assert.Equal(["work"], calls);
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
import { hrtime } from "node:process";
/**
* Runs work once and returns the time it took, in nanoseconds of clock.
* hrtime.bigint is relative to an arbitrary time in the past and is not
* related to the time of day. A bigint has no rounding.
* @param {() => unknown} work
* @param {() => bigint} [clock]
* @returns {bigint}
*/
export function measure(work, clock = hrtime.bigint) {
const start = clock();
work();
return clock() - start;
}
/**
* Returns endNs - startNs as "M.UUU ms", with the rest under one microsecond dropped.
* @param {bigint} startNs
* @param {bigint} endNs
* @returns {string}
*/
export function elapsedMs(startNs, endNs) {
const ns = endNs - startNs;
// Division of bigint values truncates, and ns is not negative.
const micros = String((ns / 1_000n) % 1_000n).padStart(3, "0");
return `${ns / 1_000_000n}.${micros} ms`;
}
elapsed.test.js 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { elapsedMs, measure } from "./elapsed.js";
const cases = [
["one-and-a-half-ms", 1000000000n, 1001500000n, "1.500 ms"],
["seconds", 0n, 2345678901n, "2345.678 ms"],
["under-one-ms", 50000n, 750000n, "0.700 ms"],
["zero", 123456789n, 123456789n, "0.000 ms"],
["under-one-microsecond", 0n, 999n, "0.000 ms"],
["truncate-not-round", 0n, 1999999n, "1.999 ms"],
["leading-zero-in-fraction", 0n, 1005000n, "1.005 ms"],
["exact-ms", 0n, 7000000n, "7.000 ms"],
["one-hour", 0n, 3600000000000n, "3600000.000 ms"],
["negative-readings", -5000000n, -3500000n, "1.500 ms"],
["across-zero", -1000000n, 500000n, "1.500 ms"],
["beyond-2-pow-53", 9007199254740993n, 9007199255741992n, "1.000 ms"],
["near-int64-max", 9223372035854775807n, 9223372036854775807n, "1000.000 ms"],
["near-int64-min", -9223372036854775808n, -9223372035854775808n, "1000.000 ms"],
];
for (const [name, startNs, endNs, want] of cases) {
test(name, () => {
assert.equal(elapsedMs(startNs, endNs), want);
});
}
test("numbers lose the difference beyond 2^53", () => {
const start = 9007199254740993n;
const end = 9007199255741992n;
assert.equal(end - start, 1000999n);
assert.equal(Number(end) - Number(start), 1001000);
});
test("measure with a fake clock", () => {
const calls = [];
const readings = [5_000_000n, 6_500_000n];
const clock = () => {
calls.push("clock");
return readings.shift();
};
assert.equal(
measure(() => calls.push("work"), clock),
1_500_000n,
);
assert.deepEqual(calls, ["clock", "work", "clock"]);
});
test("measure with the monotonic clock", () => {
const calls = [];
assert.ok(measure(() => calls.push("work")) >= 0n);
assert.deepEqual(calls, ["work"]);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
import { hrtime } from "node:process";
/**
* Runs work once and returns the time it took, in nanoseconds of clock.
* hrtime.bigint is relative to an arbitrary time in the past and is not
* related to the time of day. A bigint has no rounding.
*/
export function measure(work: () => unknown, clock: () => bigint = hrtime.bigint): bigint {
const start = clock();
work();
return clock() - start;
}
/** Returns endNs - startNs as "M.UUU ms", with the rest under one microsecond dropped. */
export function elapsedMs(startNs: bigint, endNs: bigint): string {
const ns = endNs - startNs;
// Division of bigint values truncates, and ns is not negative.
const micros = String((ns / 1_000n) % 1_000n).padStart(3, "0");
return `${ns / 1_000_000n}.${micros} ms`;
}
elapsed.test.ts 57 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
import assert from "node:assert/strict";
import { test } from "node:test";
import { elapsedMs, measure } from "./elapsed.ts";
const cases: [string, bigint, bigint, string][] = [
["one-and-a-half-ms", 1000000000n, 1001500000n, "1.500 ms"],
["seconds", 0n, 2345678901n, "2345.678 ms"],
["under-one-ms", 50000n, 750000n, "0.700 ms"],
["zero", 123456789n, 123456789n, "0.000 ms"],
["under-one-microsecond", 0n, 999n, "0.000 ms"],
["truncate-not-round", 0n, 1999999n, "1.999 ms"],
["leading-zero-in-fraction", 0n, 1005000n, "1.005 ms"],
["exact-ms", 0n, 7000000n, "7.000 ms"],
["one-hour", 0n, 3600000000000n, "3600000.000 ms"],
["negative-readings", -5000000n, -3500000n, "1.500 ms"],
["across-zero", -1000000n, 500000n, "1.500 ms"],
["beyond-2-pow-53", 9007199254740993n, 9007199255741992n, "1.000 ms"],
["near-int64-max", 9223372035854775807n, 9223372036854775807n, "1000.000 ms"],
["near-int64-min", -9223372036854775808n, -9223372035854775808n, "1000.000 ms"],
];
for (const [name, startNs, endNs, want] of cases) {
test(name, () => {
assert.equal(elapsedMs(startNs, endNs), want);
});
}
test("numbers lose the difference beyond 2^53", () => {
const start = 9007199254740993n;
const end = 9007199255741992n;
assert.equal(end - start, 1000999n);
assert.equal(Number(end) - Number(start), 1001000);
});
test("measure with a fake clock", () => {
const calls: string[] = [];
const readings = [5_000_000n, 6_500_000n];
const clock = () => {
calls.push("clock");
return readings.shift()!;
};
assert.equal(
measure(() => calls.push("work"), clock),
1_500_000n,
);
assert.deepEqual(calls, ["clock", "work", "clock"]);
});
test("measure with the monotonic clock", () => {
const calls: string[] = [];
assert.ok(measure(() => calls.push("work")) >= 0n);
assert.deepEqual(calls, ["work"]);
});
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
// Package elapsed measures the time that a piece of work takes.
package elapsed
import (
"fmt"
"time"
)
// Measure runs work once and returns the time it took. now is the clock, and
// time.Now is the real one. A Time from time.Now holds a monotonic clock
// reading, and Sub uses it when both times have one.
func Measure(work func(), now func() time.Time) time.Duration {
start := now()
work()
return now().Sub(start)
}
// ElapsedMs returns endNs - startNs as "M.UUU ms", with the rest under one
// microsecond dropped.
func ElapsedMs(startNs, endNs int64) string {
ns := endNs - startNs
// Integer division truncates, and ns is not negative.
return fmt.Sprintf("%d.%03d ms", ns/1_000_000, ns/1_000%1_000)
}
elapsed_test.go 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
package elapsed
import (
"math"
"slices"
"testing"
"time"
)
var cases = []struct {
name string
startNs, endNs int64
want string
}{
{"one-and-a-half-ms", 1000000000, 1001500000, "1.500 ms"},
{"seconds", 0, 2345678901, "2345.678 ms"},
{"under-one-ms", 50000, 750000, "0.700 ms"},
{"zero", 123456789, 123456789, "0.000 ms"},
{"under-one-microsecond", 0, 999, "0.000 ms"},
{"truncate-not-round", 0, 1999999, "1.999 ms"},
{"leading-zero-in-fraction", 0, 1005000, "1.005 ms"},
{"exact-ms", 0, 7000000, "7.000 ms"},
{"one-hour", 0, 3600000000000, "3600000.000 ms"},
{"negative-readings", -5000000, -3500000, "1.500 ms"},
{"across-zero", -1000000, 500000, "1.500 ms"},
{"beyond-2-pow-53", 9007199254740993, 9007199255741992, "1.000 ms"},
{"near-int64-max", 9223372035854775807, 9223372036854775807, "1000.000 ms"},
{"near-int64-min", math.MinInt64, -9223372035854775808, "1000.000 ms"},
}
func TestElapsedMs(t *testing.T) {
for _, c := range cases {
t.Run(c.name, func(t *testing.T) {
if got := ElapsedMs(c.startNs, c.endNs); got != c.want {
t.Errorf("ElapsedMs(%d, %d) = %q, want %q", c.startNs, c.endNs, got, c.want)
}
})
}
}
func TestMeasureWithAFakeClock(t *testing.T) {
var calls []string
readings := []time.Time{time.Unix(0, 5_000_000), time.Unix(0, 6_500_000)}
now := func() time.Time {
calls = append(calls, "clock")
r := readings[0]
readings = readings[1:]
return r
}
if got := Measure(func() { calls = append(calls, "work") }, now); got != 1500*time.Microsecond {
t.Errorf("Measure = %v, want 1.5ms", got)
}
if want := []string{"clock", "work", "clock"}; !slices.Equal(calls, want) {
t.Errorf("calls = %v, want %v", calls, want)
}
}
func TestMeasureWithTheMonotonicClock(t *testing.T) {
var calls []string
if got := Measure(func() { calls = append(calls, "work") }, time.Now); got < 0 {
t.Errorf("Measure = %v, want >= 0", got)
}
if want := []string{"work"}; !slices.Equal(calls, want) {
t.Errorf("calls = %v, want %v", calls, want)
}
}
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
//! Measures the time that a piece of work takes.
use std::time::{Duration, Instant};
/// Runs `work` once and returns the time it took. `now` is the clock, and
/// `Instant::now` is the real one. An `Instant` is monotonic, and it has a
/// meaning only next to another `Instant`.
pub fn measure(work: impl FnOnce(), mut now: impl FnMut() -> Instant) -> Duration {
let start = now();
work();
now().duration_since(start)
}
/// Returns `end_ns - start_ns` as "M.UUU ms", with the rest under one
/// microsecond dropped.
pub fn elapsed_ms(start_ns: i64, end_ns: i64) -> String {
let ns = end_ns - start_ns;
// Integer division truncates, and ns is not negative.
format!("{}.{:03} ms", ns / 1_000_000, ns / 1_000 % 1_000)
}
tests/elapsed_test.rs 69 lines
// SPDX-License-Identifier: MIT
// Part of https://programming.tamnd.com/measure-elapsed-time/.
use std::cell::RefCell;
use std::time::{Duration, Instant};
use algo_measure_elapsed_time::{elapsed_ms, measure};
const CASES: &[(&str, i64, i64, &str)] = &[
("one-and-a-half-ms", 1000000000, 1001500000, "1.500 ms"),
("seconds", 0, 2345678901, "2345.678 ms"),
("under-one-ms", 50000, 750000, "0.700 ms"),
("zero", 123456789, 123456789, "0.000 ms"),
("under-one-microsecond", 0, 999, "0.000 ms"),
("truncate-not-round", 0, 1999999, "1.999 ms"),
("leading-zero-in-fraction", 0, 1005000, "1.005 ms"),
("exact-ms", 0, 7000000, "7.000 ms"),
("one-hour", 0, 3600000000000, "3600000.000 ms"),
("negative-readings", -5000000, -3500000, "1.500 ms"),
("across-zero", -1000000, 500000, "1.500 ms"),
(
"beyond-2-pow-53",
9007199254740993,
9007199255741992,
"1.000 ms",
),
(
"near-int64-max",
9223372035854775807,
9223372036854775807,
"1000.000 ms",
),
(
"near-int64-min",
i64::MIN,
-9223372035854775808,
"1000.000 ms",
),
];
#[test]
fn elapsed_ms_cases() {
for &(name, start_ns, end_ns, want) in CASES {
assert_eq!(elapsed_ms(start_ns, end_ns), want, "{name}");
}
}
#[test]
fn measure_with_a_fake_clock() {
// An Instant cannot be made from a number, so the fake readings are offsets from one real Instant.
let base = Instant::now();
let calls = RefCell::new(Vec::new());
let mut readings = [5_000_000, 6_500_000].into_iter();
let now = || {
calls.borrow_mut().push("clock");
base + Duration::from_nanos(readings.next().unwrap())
};
let got = measure(|| calls.borrow_mut().push("work"), now);
assert_eq!(got, Duration::from_micros(1_500));
assert_eq!(*calls.borrow(), ["clock", "work", "clock"]);
}
#[test]
fn measure_with_the_monotonic_clock() {
let mut calls = Vec::new();
let got = measure(|| calls.push("work"), Instant::now);
assert!(got >= Duration::ZERO);
assert_eq!(calls, ["work"]);
}
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/measure-elapsed-time/.
# monotonic_ns prints a reading of the monotonic clock in nanoseconds. Bash has
# BASH_MONOSECONDS, which counts whole seconds, so the reading is a multiple
# of 10^9.
monotonic_ns() {
printf '%s\n' "$((BASH_MONOSECONDS * 1000000000))"
}
# measure CLOCK COMMAND [ARG...] runs the command once and prints the time it
# took, in nanoseconds of CLOCK. CLOCK is a command that prints a reading,
# such as monotonic_ns. The output of the command goes to stderr, and its exit
# status is the status of measure.
measure() {
local clock=$1 start end status
shift
start=$("$clock") || return
"$@" >&2
status=$?
end=$("$clock") || return
printf '%s\n' "$((end - start))"
return "$status"
}
# elapsed_ms START_NS END_NS prints END_NS - START_NS as "M.UUU ms", with the
# rest under one microsecond dropped.
elapsed_ms() {
# Bash arithmetic has integers only, so / drops the fraction.
local ns=$(($2 - $1))
printf '%d.%03d ms\n' "$((ns / 1000000))" "$((ns / 1000 % 1000))"
}
test_elapsed.bats 57 lines
#!/usr/bin/env bats
# SPDX-License-Identifier: MIT
# Part of https://programming.tamnd.com/measure-elapsed-time/.
setup() {
source "$BATS_TEST_DIRNAME/elapsed.sh"
}
@test "one-and-a-half-ms" { run elapsed_ms 1000000000 1001500000; [ "$status" -eq 0 ]; [ "$output" = "1.500 ms" ]; }
@test "seconds" { run elapsed_ms 0 2345678901; [ "$status" -eq 0 ]; [ "$output" = "2345.678 ms" ]; }
@test "under-one-ms" { run elapsed_ms 50000 750000; [ "$status" -eq 0 ]; [ "$output" = "0.700 ms" ]; }
@test "zero" { run elapsed_ms 123456789 123456789; [ "$status" -eq 0 ]; [ "$output" = "0.000 ms" ]; }
@test "under-one-microsecond" { run elapsed_ms 0 999; [ "$status" -eq 0 ]; [ "$output" = "0.000 ms" ]; }
@test "truncate-not-round" { run elapsed_ms 0 1999999; [ "$status" -eq 0 ]; [ "$output" = "1.999 ms" ]; }
@test "leading-zero-in-fraction" { run elapsed_ms 0 1005000; [ "$status" -eq 0 ]; [ "$output" = "1.005 ms" ]; }
@test "exact-ms" { run elapsed_ms 0 7000000; [ "$status" -eq 0 ]; [ "$output" = "7.000 ms" ]; }
@test "one-hour" { run elapsed_ms 0 3600000000000; [ "$status" -eq 0 ]; [ "$output" = "3600000.000 ms" ]; }
@test "negative-readings" { run elapsed_ms -5000000 -3500000; [ "$status" -eq 0 ]; [ "$output" = "1.500 ms" ]; }
@test "across-zero" { run elapsed_ms -1000000 500000; [ "$status" -eq 0 ]; [ "$output" = "1.500 ms" ]; }
@test "beyond-2-pow-53" { run elapsed_ms 9007199254740993 9007199255741992; [ "$status" -eq 0 ]; [ "$output" = "1.000 ms" ]; }
@test "near-int64-max" { run elapsed_ms 9223372035854775807 9223372036854775807; [ "$status" -eq 0 ]; [ "$output" = "1000.000 ms" ]; }
@test "near-int64-min" { run elapsed_ms -9223372036854775808 -9223372035854775808; [ "$status" -eq 0 ]; [ "$output" = "1000.000 ms" ]; }
# fake_clock prints the next line of $BATS_TEST_TMPDIR/readings. measure runs
# the clock in a subshell, so the position is kept in a file.
fake_clock() {
local n
n=$(<"$BATS_TEST_TMPDIR/next")
echo "$((n + 1))" >"$BATS_TEST_TMPDIR/next"
echo clock >>"$BATS_TEST_TMPDIR/calls"
sed -n "$((n + 1))p" "$BATS_TEST_TMPDIR/readings"
}
work() {
echo work >>"$BATS_TEST_TMPDIR/calls"
}
@test "measure with a fake clock" {
printf '%s\n' 5000000 6500000 >"$BATS_TEST_TMPDIR/readings"
echo 0 >"$BATS_TEST_TMPDIR/next"
run measure fake_clock work
[ "$status" -eq 0 ]
[ "$output" = 1500000 ]
[ "$(paste -sd ' ' "$BATS_TEST_TMPDIR/calls")" = "clock work clock" ]
}
@test "measure with the monotonic clock" {
run measure monotonic_ns work
[ "$status" -eq 0 ]
((output >= 0))
[ "$(<"$BATS_TEST_TMPDIR/calls")" = work ]
}
@test "measure returns the status of the command" {
run measure monotonic_ns false
[ "$status" -eq 1 ]
}
References
- The Python Standard Library, time, time.monotonic, time.monotonic_ns, time.time
- Node.js documentation, process, process.hrtime([time]); process.hrtime.bigint()
- Node.js documentation, Performance measurement APIs, performance.now()
- Java SE 25 API, java.lang.System, nanoTime(); currentTimeMillis()
- Java SE 25 API, java.util.Formatter, Number Localization Algorithm
- .NET API reference, TimeProvider, Remarks; Properties (System, TimestampFrequency); Methods (GetElapsedTime, GetTimestamp)
- .NET API reference, Stopwatch.GetTimestamp, Remarks
- Go standard library, time, Overview, Monotonic Clocks; func (Time) String
- The Rust Standard Library, std::time::Instant, Description; duration_since; checked_duration_since
- The Open Group Base Specifications Issue 8, clock_getres, clock_gettime, clock_settime, DESCRIPTION, CLOCK_MONOTONIC
- cppreference.com, clock, the description of clock
- cppreference.com, std::chrono::steady_clock, the description of the class
- cppreference.com, std::chrono::high_resolution_clock, the description of the class
- GNU Bash Reference Manual, 5.2 Bash Variables: BASH_MONOSECONDS, EPOCHREALTIME; 6.5 Shell Arithmetic
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.
| Ladder | Level | What the next level needs |
|---|---|---|
| Human proof | H0 no proof |
|
| Lean | L0 no Lean part |
|
| Code (bash) | I0 not checked yet |
|
| Code (c) | I0 not checked yet |
|
| Code (cpp) | I0 not checked yet |
|
| Code (csharp) | I0 not checked yet |
|
| Code (go) | I0 not checked yet |
|
| Code (java) | I0 not checked yet |
|
| Code (javascript) | I0 not checked yet |
|
| Code (python) | I0 not checked yet |
|
| Code (rust) | I0 not checked yet |
|
| Code (typescript) | I0 not checked yet |
|
| Visual | V0 none |
|
| Writing | W3 standard |
|
The native tests pass in 9 of 10 languages in this build.
Tag G63EVZ Edit this page History Report an error Markdown