npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

@synet/timer

v1.0.0

Published

High-precision timing and performance measurement with Unit Architecture

Downloads

5

Readme

Timer Unit 🚀

  _______ _                       _    _       _ _   
 |__   __(_)                     | |  | |     (_) |  
    | |   _ _ __ ___   ___ _ __  | |  | |_ __  _| |_ 
    | |  | | '_ ` _ \ / _ \ '__| | |  | | '_ \| | __|
    | |  | | | | | | |  __/ |    | |__| | | | | | |_ 
    |_|  |_|_| |_| |_|\___|_|     \____/|_| |_|_|\__|
                                                     
                                                     
version: 1.0.0.                                                    

High-precision timing and performance measurement with Unit Architecture

Simple, immutable, and composable timing operations for Node.js applications. Built on Unit Architecture principles - no external dependencies, zero mutation, maximum precision.

Quick Start

import { Timer, timeFunction, sleep, measure } from '@synet/timer';

// Basic timing
const timer = Timer.create().start('operation');
// ... do work ...
const { timer: stopped, measurement } = timer.stop();
console.log(`Operation took: ${measurement.duration.toFixed(2)}ms`);

// Function timing
const { result, measurement } = await timeFunction(() => {
  return expensiveCalculation();
}, 'calculation');

// Async delays
await Timer.sleep(1000); // 1 second delay

// Quick measurements
const { result, duration } = measure(() => fastOperation(), 'fast-op');

Features

Immutable Design

  • No state mutation - every operation returns new instances
  • Thread-safe by design
  • Preserves measurement history across operations

High Precision

  • Uses performance.now() for microsecond accuracy
  • Configurable decimal precision for display
  • Handles both sync and async operations

Performance Analytics

  • Automatic measurement accumulation
  • Built-in statistics (min, max, average, total)
  • Benchmarking with warmup runs
  • Multiple measurement tracking

Unit Architecture

  • Self-aware units with teaching/learning capabilities
  • Zero external dependencies
  • Composable with other units
  • Built-in help and documentation

Installation

npm install @synet/timer

Core API

Timer Creation

// Basic timer
const timer = Timer.create();

// Configured timer
const timer = Timer.create({
  label: 'MyTimer',
  precision: 3,        // 3 decimal places
  metadata: { app: 'test' }
});

Timing Operations

// Start/stop pattern
const running = timer.start('measurement-1');
// ... work ...
const { timer: next, measurement } = running.stop();

// Multiple measurements
let current = Timer.create();
for (let i = 0; i < 5; i++) {
  const running = current.start(`lap-${i}`);
  await doWork();
  const { timer: updated } = running.stop();
  current = updated;
}

console.log(`Total measurements: ${current.measurementCount}`);
console.log(`Statistics:`, current.getStats());

Function Timing

// Time any function
const { result, measurement } = await Timer.timeFunction(async () => {
  const response = await fetch('/api/data');
  return response.json();
}, 'api-call');

console.log(`API call: ${measurement.duration.toFixed(2)}ms`);
console.log(`Result:`, result);

Benchmarking

// Performance benchmarks
const benchmark = await Timer.benchmark(() => {
  return complexAlgorithm(data);
}, {
  iterations: 100,
  warmup: 10,
  label: 'algorithm-test'
});

console.log(`Average: ${benchmark.average.toFixed(2)}ms`);
console.log(`Min: ${benchmark.min.toFixed(2)}ms`);
console.log(`Max: ${benchmark.max.toFixed(2)}ms`);

Statistics & Analysis

const timer = Timer.create();
// ... perform multiple measurements ...

const stats = timer.getStats();
if (stats) {
  console.log(`Total measurements: ${stats.count}`);
  console.log(`Total time: ${stats.total.toFixed(2)}ms`);
  console.log(`Average: ${stats.average.toFixed(2)}ms`);
  console.log(`Range: ${stats.min.toFixed(2)}ms - ${stats.max.toFixed(2)}ms`);
}

// Get all measurements
const measurements = timer.getMeasurements();
measurements.forEach(m => {
  console.log(`${m.label}: ${m.duration.toFixed(2)}ms`);
});

Convenience Functions

import { createTimer, timeFunction, sleep, measure } from '@synet/timer';

// Quick timer creation
const timer = createTimer('MyApp', 3);

// One-off function timing
const { result } = await timeFunction(() => calculation(), 'calc');

// Async delays
await sleep(500); // 500ms delay

// Instant measurement with console output
const { result } = measure(() => fastFunction(), 'fast-test');
// Output: ⚡ fast-test: 0.12ms

Unit Architecture Integration

Teaching & Learning

// Timer can teach its capabilities to other units
const timer = Timer.create();
const contract = timer.teach();

// Other units can learn timing capabilities
otherUnit.learn([contract]);

// Now other unit can time operations
if (otherUnit.can('timer.start')) {
  const result = otherUnit.execute('timer.start', 'operation');
}

Self-Documentation

// Every timer is self-documenting
timer.help();
// Outputs comprehensive usage information

console.log(timer.whoami());
// "Timer Unit - MyTimer ([email protected])"

console.log(timer.capabilities());
// ["elapsed", "start", "stop", "toJSON"]

JSON Export

const exported = timer.toJSON();
// {
//   unitId: 'timer',
//   version: '1.0.0',
//   label: 'MyTimer',
//   measurements: [...],
//   isRunning: false,
//   created: '2025-07-30T14:50:00.000Z'
// }

Real-World Examples

API Performance Monitoring

import { Timer } from '@synet/timer';

class APIMonitor {
  private timer = Timer.create({ label: 'API-Monitor' });

  async monitorEndpoint(url: string) {
    const { result, measurement } = await Timer.timeFunction(async () => {
      const response = await fetch(url);
      return response.json();
    }, `GET-${url}`);

    if (measurement.duration > 1000) {
      console.warn(`Slow API: ${url} took ${measurement.duration.toFixed(2)}ms`);
    }

    return result;
  }
}

Database Query Profiling

async function profileQuery(query: string) {
  const timer = Timer.create({ label: 'DB-Profile' });
  
  const running = timer.start(query);
  const result = await db.execute(query);
  const { measurement } = running.stop();
  
  await logMetric({
    query,
    duration: measurement.duration,
    timestamp: measurement.endTime
  });
  
  return result;
}

Build Process Timing

async function buildWithTiming() {
  let timer = Timer.create({ label: 'Build-Process' });
  
  // Compile TypeScript
  timer = timer.start('compile-ts');
  await runTSC();
  const { timer: afterTS } = timer.stop();
  
  // Bundle assets
  const bundling = afterTS.start('bundle-assets');
  await runWebpack();
  const { timer: final } = bundling.stop();
  
  // Report
  const stats = final.getStats();
  console.log(`Build completed in ${stats?.total.toFixed(2)}ms`);
  
  final.getMeasurements().forEach(m => {
    console.log(`  ${m.label}: ${m.duration.toFixed(2)}ms`);
  });
}

Architecture Principles

This Timer Unit follows Unit Architecture principles:

  • Immutable Evolution - Operations create new instances, never mutate
  • Zero Dependencies - Pure implementation using only Node.js built-ins
  • Teaching Contracts - Can share capabilities with other units
  • Props-Based State - Single source of truth in immutable props
  • Self-Documenting - Built-in help and introspection

TypeScript Support

Full TypeScript support with strict typing:

// Generic function timing
const { result, measurement } = await Timer.timeFunction<UserData[]>(
  () => fetchUsers(),
  'user-fetch'
);
// result is typed as UserData[]

// Type-safe configuration
const timer: Timer = Timer.create({
  label: 'TypedTimer',
  precision: 2,
  metadata: { version: '1.0.0' }
});

Contributing

Built with love by the SYNET team. Part of the larger Unit Architecture ecosystem.

License

MIT - Build amazing things!