AlgoViz

Latency

easy 30 min

Latency is how long one request takes.

Measure and summarise latency

Read it, run it, change a line and run it again.

Loading editor…

Nearest-rank percentiles: P99 of 100 values is the 99th, not the 100th. Keeping every value is fine for a test; production uses histogram buckets.

The same in TypeScript
interface LatencyStats { count: number; minMs: number; maxMs: number; avgMs: number; p50Ms: number; p95Ms: number; p99Ms: number }class LatencyCollector {  private values: number[] = [];  constructor(readonly name: string) {}  record(ms: number): void { this.values.push(ms); }  reset(): void { this.values = []; }  stats(): LatencyStats {    const v = [...this.values].sort((a, b) => a - b);    if (v.length === 0) return { count: 0, minMs: 0, maxMs: 0, avgMs: 0, p50Ms: 0, p95Ms: 0, p99Ms: 0 };    const at = (p: number) => v[Math.max(1, Math.ceil((v.length * p) / 100)) - 1];    const sum = v.reduce((a, b) => a + b, 0);    return { count: v.length, minMs: v[0], maxMs: v[v.length - 1], avgMs: sum / v.length, p50Ms: at(50), p95Ms: at(95), p99Ms: at(99) };  }}class LatencyHistogram {  private buckets = new Map<number, number>();  constructor(private width = 10) {}  record(ms: number): void {    const b = Math.floor(ms / this.width) * this.width;    this.buckets.set(b, (this.buckets.get(b) ?? 0) + 1);  }  print(): void {    const rows = [...this.buckets].sort((a, b) => a[0] - b[0]);    const most = Math.max(...rows.map((r) => r[1]));    for (const [b, n] of rows) console.log(String(b).padStart(4) + " ms " + "#".repeat(Math.round((n / most) * 40)) + " " + n);  }}function measureSync<T>(fn: () => T, c: LatencyCollector): T {  const start = performance.now();  try { return fn(); } finally { c.record(performance.now() - start); }}async function measureAsync<T>(fn: () => Promise<T>, c: LatencyCollector): Promise<T> {  const start = performance.now();  try { return await fn(); } finally { c.record(performance.now() - start); }}async function main() {  const c = new LatencyCollector("api-calls");  for (let i = 0; i < 100; i++) await measureAsync(() => new Promise<void>((r) => setTimeout(r, Math.random() * 20)), c);  console.log(measureSync(() => c.stats(), c));  const h = new LatencyHistogram(100);  [...Array(90).fill(10), ...Array(10).fill(410)].forEach((ms) => h.record(ms));  h.print();}main();
The same in Go
package mainimport (	"fmt"	"math"	"sort"	"sync"	"time")type Stats struct {	Count                         int	Min, Max, Avg, P50, P95, P99  float64}type Collector struct {	mu     sync.Mutex	values []float64}func (c *Collector) Record(d time.Duration) {	c.mu.Lock()	defer c.mu.Unlock()	c.values = append(c.values, float64(d.Microseconds())/1000)}func (c *Collector) Stats() Stats {	c.mu.Lock()	v := append([]float64(nil), c.values...) // copy, then sort without the lock	c.mu.Unlock()	if len(v) == 0 {		return Stats{}	}	sort.Float64s(v)	sum := 0.0	for _, x := range v {		sum += x	}	at := func(p float64) float64 {		i := int(math.Ceil(float64(len(v))*p/100)) - 1		if i < 0 {			i = 0		}		return v[i]	}	return Stats{len(v), v[0], v[len(v)-1], sum / float64(len(v)), at(50), at(95), at(99)}}type Timer struct {	start time.Time	c     *Collector}func NewTimer(c *Collector) Timer { return Timer{time.Now(), c} }func (t Timer) Stop()             { t.c.Record(time.Since(t.start)) }func main() {	c := &Collector{}	for i := 0; i < 100; i++ {		t := NewTimer(c)		time.Sleep(time.Millisecond * time.Duration(1+i%10))		t.Stop()	}	fmt.Printf("%+v\n", c.Stats())}
The same in Java
import java.util.*;public class Latency {    record Stats(int count, double min, double max, double avg, double p50, double p95, double p99) {}    static class Collector {        private final List<Double> values = new ArrayList<>();        synchronized void recordNanos(long nanos) { values.add(nanos / 1_000_000.0); }        synchronized void reset() { values.clear(); }        synchronized Stats stats() {            if (values.isEmpty()) return new Stats(0, 0, 0, 0, 0, 0, 0);            List<Double> v = new ArrayList<>(values);            Collections.sort(v);            double avg = v.stream().mapToDouble(x -> x).average().orElse(0);            return new Stats(v.size(), v.get(0), v.get(v.size() - 1), avg, at(v, 50), at(v, 95), at(v, 99));        }        private static double at(List<Double> sorted, double p) {            int rank = (int) Math.ceil(sorted.size() * p / 100);            return sorted.get(Math.max(1, rank) - 1);        }    }    record Timer(Collector c, long start) implements AutoCloseable {        static Timer on(Collector c) { return new Timer(c, System.nanoTime()); }        @Override public void close() { c.recordNanos(System.nanoTime() - start); }    }    public static void main(String[] args) throws Exception {        Collector c = new Collector();        Random random = new Random();        for (int i = 0; i < 100; i++) {            try (Timer t = Timer.on(c)) { Thread.sleep(1 + random.nextInt(10)); }        }        System.out.println(c.stats());    }}