npm package: @synet/timer
Description: High-precision timing and performance measurement with Unit Architecture
Author: Synet Team
Latest version: 1.0.0

# Timer Unit 🚀

```bash
  _______ _                       _    _       _ _   
 |__   __(_)                     | |  | |     (_) |  
    | |   _ _ __ ___   ___ _ __  | |  | |_ __  _| |_ 
    | |  | | '_ ` _ \ / _ \ '__| | |  | | '_ \| | __|
    | |  | | | | | | |  __/ |    | |__| | | | | | |_ 
    |_|  |_|_| |_| |_|\___|_|     \____/|_| |_|_|\__|
                                                     
                                                     
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

```typescript
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

```bash
npm install @synet/timer
```

## Core API

### Timer Creation

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

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

### Timing Operations

```typescript
// 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

```typescript
// 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

```typescript
// 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

```typescript
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

```typescript
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

```typescript
// 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

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

console.log(timer.whoami());
// "Timer Unit - MyTimer (timer@1.0.0)"

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

### JSON Export

```typescript
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

```typescript
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

```typescript
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

```typescript
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](https://github.com/synthetism/unit) 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:

```typescript
// 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.

- **Issues**: [GitHub Issues](https://github.com/synthetism/synet/issues)
- **Docs**: [Unit Architecture Guide](https://github.com/synthetism/unit)

## License

MIT - Build amazing things!