Skip to content

Profiler

Sebastian Martinez edited this page Mar 28, 2026 · 6 revisions

⏱️ Profiler

EN: Performance measurement utilities. Includes a label-based Profiler class for tracking named operations and standalone debug functions (createStopwatch, withTiming, measureSync, measureAsync, captureDebug) for precise time measurement.

ES: Utilidades de medición de rendimiento. Incluye una clase Profiler basada en etiquetas para rastrear operaciones nombradas y funciones independientes de debug (createStopwatch, withTiming, measureSync, measureAsync, captureDebug) para medición precisa de tiempo.


📦 Import

// Profiler class / Clase Profiler
import { Profiler } from "bytekit/profiler";

// Debug utilities (standalone functions) / Utilidades de debug (funciones independientes)
import {
  createStopwatch,
  withTiming,
  measureSync,
  measureAsync,
  captureDebug,
} from "bytekit/debug";

// or import everything / o importar todo:
import { Profiler, createStopwatch, withTiming /* ... */ } from "bytekit";

Part 1 — Profiler Class / Parte 1 — Clase Profiler

EN: Simple label-based profiler that records execution times. Uses performance.now() for high-resolution timing. Without a namespace, summary() returns a flat object; with a namespace, it returns a nested object keyed by namespace.

ES: Perfilador simple basado en etiquetas que registra tiempos de ejecución. Usa performance.now() para temporización de alta resolución. Sin namespace, summary() devuelve un objeto plano; con namespace, devuelve un objeto anidado por namespace.

⚙️ Constructor

const profiler = new Profiler(namespace?: string);
Parameter / Parámetro Type / Tipo Default Description (EN) Descripción (ES)
namespace string undefined Optional grouping key for results Clave opcional para agrupar resultados

📋 Methods / Métodos

Method / Método Signature / Firma Description (EN) Descripción (ES)
start start(label: string): void Begins timing a labelled operation Inicia la medición de una operación etiquetada
end end(label: string): void Ends timing and records the duration in ms Finaliza la medición y registra la duración en ms
summary summary(): Record<string, number> | Record<string, Record<string, number>> Returns all recorded durations Devuelve todas las duraciones registradas

💡 Examples / Ejemplos

Without namespace (flat) / Sin namespace (plano)

import { Profiler } from "bytekit/profiler";

const profiler = new Profiler();

profiler.start("fetchUsers");
await fetchUsers();
profiler.end("fetchUsers");

profiler.start("renderUI");
renderDashboard();
profiler.end("renderUI");

console.log(profiler.summary());
// { fetchUsers: 234.56, renderUI: 12.34 }

With namespace (nested) / Con namespace (anidado)

const profiler = new Profiler("api-layer");

profiler.start("GET /users");
await fetch("/api/users");
profiler.end("GET /users");

profiler.start("GET /posts");
await fetch("/api/posts");
profiler.end("GET /posts");

console.log(profiler.summary());
// { "api-layer": { "GET /users": 189.3, "GET /posts": 45.7 } }

Part 2 — Debug Utilities / Parte 2 — Utilidades de Debug

EN: Standalone timing functions for measuring individual operations. These are not methods of Profiler — they are independent exports from bytekit/debug. They use performance.now() when available, falling back to Date.now().

ES: Funciones independientes de temporización para medir operaciones individuales. No son métodos de Profiler — son exports independientes de bytekit/debug. Usan performance.now() cuando está disponible, con fallback a Date.now().


🔧 StopwatchOptions

interface StopwatchOptions {
  label?: string;      // Descriptive label / Etiqueta descriptiva
  logger?: Logger;     // Logger instance for auto-logging / Instancia de Logger para auto-logging
  precision?: number;  // Decimal places in logs (default: 2) / Decimales en los logs (default: 2)
  autoLog?: boolean;   // Log automatically on stop() / Loguear automáticamente al detener
  namespace?: string;  // Creates a child logger / Crea un logger hijo
}

🔧 Stopwatch

interface Stopwatch {
  stop(): number;                             // Stops and returns duration in ms / Detiene y retorna duración en ms
  elapsed(): number;                          // Returns elapsed time without stopping / Retorna tiempo transcurrido sin detener
  log(context?: Record<string, unknown>): number; // Stops, logs, and returns duration / Detiene, loguea y retorna duración
}

📋 Functions / Funciones

Function / Función Signature / Firma Description (EN) Descripción (ES)
createStopwatch createStopwatch(options?: StopwatchOptions): Stopwatch Creates a manual stopwatch Crea un cronómetro manual
withTiming withTiming<T>(label, fn, options?): Promise<T> Runs a function (sync or async) and logs its duration Ejecuta una función (sync o async) y registra su duración
measureSync measureSync<T>(label, fn, options?): T Synchronous version of withTiming Versión síncrona de withTiming
measureAsync measureAsync<T>(label, fn, options?): Promise<{ result: T, durationMs: number }> Async execution returning result + duration Ejecución async que retorna resultado + duración
captureDebug captureDebug<T>(fn): Promise<{ result: T, durationMs: number }> Logger-free capture — returns raw timing data Captura sin logger — retorna datos de temporización crudos

💡 Examples / Ejemplos

createStopwatch

import { createStopwatch } from "bytekit/debug";

const sw = createStopwatch({ label: "db-query", autoLog: false });

await database.query("SELECT * FROM users");

const ms = sw.stop();
console.log(`Query took ${ms.toFixed(2)}ms`);
// Query took 42.17ms

createStopwatch with Logger / createStopwatch con Logger

import { createStopwatch } from "bytekit/debug";
import { Logger } from "bytekit/logger";

const logger = new Logger({ level: "debug" });
const sw = createStopwatch({ label: "api-call", logger, autoLog: true });

await fetch("/api/data");
sw.stop(); // Automatically logs: "api-call took 123.45ms"
           // Loguea automáticamente: "api-call took 123.45ms"

withTiming

import { withTiming } from "bytekit/debug";

// Runs fn and logs duration; returns fn's result
// Ejecuta fn y loguea la duración; retorna el resultado de fn
const users = await withTiming("fetchUsers", async () => {
  const res = await fetch("/api/users");
  return res.json();
});

measureSync

import { measureSync } from "bytekit/debug";

// Synchronous measurement / Medición síncrona
const sorted = measureSync("sortArray", () => {
  return largeArray.sort((a, b) => a - b);
});

measureAsync

import { measureAsync } from "bytekit/debug";

// Returns both result and duration / Retorna resultado y duración
const { result, durationMs } = await measureAsync("loadConfig", async () => {
  return JSON.parse(await fs.readFile("config.json", "utf-8"));
});

console.log(`Config loaded in ${durationMs}ms`, result);

captureDebug

import { captureDebug } from "bytekit/debug";

// No logger needed — just captures raw timing
// Sin logger — solo captura temporización cruda
const { result, durationMs } = await captureDebug(async () => {
  return await expensiveComputation();
});

if (durationMs > 1000) {
  console.warn("Slow operation detected!");
}

🧠 How It Works / Cómo Funciona

EN: All timing functions use performance.now() for sub-millisecond precision in browsers and Node.js. If performance is unavailable, they fall back to Date.now(). The Profiler class maintains an internal stack, matching start(label) → end(label) pairs in LIFO order. The debug utilities are stateless — each createStopwatch() call is independent.

ES: Todas las funciones de temporización usan performance.now() para precisión sub-milisegundo en navegadores y Node.js. Si performance no está disponible, recurren a Date.now(). La clase Profiler mantiene una pila interna, emparejando start(label) → end(label) en orden LIFO. Las utilidades de debug son stateless — cada llamada a createStopwatch() es independiente.

Profiler                          Debug Utilities
┌──────────────────────┐          ┌──────────────────────┐
│  start("A")          │          │  createStopwatch()   │
│  start("B")          │          │    → { stop, elapsed,│
│  end("B") → record B │          │        log }         │
│  end("A") → record A │          │                      │
│  summary() → { A, B }│          │  withTiming(label,fn)│
└──────────────────────┘          │  measureSync(label,fn│
                                  │  measureAsync(…)     │
                                  │  captureDebug(fn)    │
                                  └──────────────────────┘

Véase También / See Also

  • Logger — Structured logging used by debug utilities / Registro estructurado usado por utilidades de debug
  • ApiClient — HTTP client with built-in timing / Cliente HTTP con temporización integrada
  • ErrorBoundary — Error handling with retry metrics / Manejo de errores con métricas de reintento

Clone this wiki locally