# API `@deepkit/bench`

```sh
npm install @deepkit/bench
```

코드 스니펫을 벤치마크하기 위한 간단한 도구입니다.

```typescript
import { benchmark, run } from '@deepkit/bench';

// ASCII 바이너리 파싱 예제
const binaryString = Buffer.from('Hello World', 'utf8');
const codes = [

benchmark('Buffer.toString', () => {
    const utf8String = binaryString.toString('utf8');
});

benchmark('String.fromCodePoint', () => {
    const utf8String = String.fromCodePoint()
});

void run();
```

```sh
$ node --import @deepkit/run benchmarks/ascii-parsing.ts
Node v22.13.1
 🏎 x  20,326,482.53 ops/sec ± 4.95%   0.000049 ms/op 	▆▆▇▅▆▆▅▅▆▅▅▅▅▅▅▅▅▅▅▅▅▅ Buffer.toString 	19850001 samples
 🏎 x  36,012,545.69 ops/sec ± 1.78%   0.000028 ms/op 	▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇▇ String.fromCodePoint 	35800001 samples
done
```

## API reference of @deepkit/bench

### getBlockBar (function)

Creates a colored block bar visualization from sample data.
Uses HSV color gradient (green -> yellow) based on value.

```typescript
(values: number[], width?: number): string
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L151

### getBrailleBar (function)

Creates a Braille-based bar visualization (more compact).

```typescript
(values: number[]): string
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L176

### formatHz (function)

Formats operations per second with K/M/B suffix.

```typescript
(v: number): string
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L206

### formatHzFull (function)

Formats operations per second with full number and locale formatting.

```typescript
(v: number): string
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L216

### formatMean (function)

Formats mean time per operation with appropriate unit (ns, µs, ms, s).

```typescript
(ms: number): string
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L223

### formatRme (function)

Formats relative margin of error as percentage.

```typescript
(v: number): string
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L233

### formatBytes (function)

Formats bytes with appropriate unit (B, KB, MB).

```typescript
(bytes: number): string
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L240

### benchmark (function)

Registers a benchmark with the given name and function.
Function can be synchronous or asynchronous.

```typescript
(name: string, fn: () => void | Promise<void>): void
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L731

### run (function)

Runs all registered benchmarks each for the given number of seconds.

```typescript
(seconds?: number): Promise<void>
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L750

### forceGC (function)

Forces garbage collection if --expose-gc flag was used.

```typescript
(): void
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L889

### getHeapUsage (function)

Gets current heap memory usage in bytes.

```typescript
(): number
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L896

### warmup (function)

Warmup function for V8 optimization.
Run a function multiple times to ensure V8 optimizes it before benchmarking.

```typescript
(fn: () => unknown, times?: number): void
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L907

### warmupAsync (function)

Async warmup function for V8 optimization.

```typescript
(fn: () => Promise<unknown>, times?: number): Promise<void>
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L919

### BenchResult (type)

Result of a single benchmark

```typescript
// TYPES
// ══════════════════════════════════════════════════════════════════════════════

/**
 * Result of a single benchmark
 */
export interface BenchResult {
    /** Operations per second */
    hz: number;
    /** Total elapsed time in seconds */
    elapsed: number;
    /** Relative margin of error (as percentage) */
    rme: number;
    /** Mean time per operation in milliseconds */
    mean: number;
    /** Variance of samples */
    variance: number;
    /** Number of iterations run */
    iterations: number;
    /** Sample timings for visualization (up to 50 samples) */
    samples: number[];
    /** Heap memory difference in bytes */
    heapDiff: number;
    /** Whether this is an async benchmark */
    async: boolean;
    /** GC events during benchmark (pause times in ms) */
    gcEvents: number[];
}
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L35

### BenchSuiteResult (type)

Results of a benchmark suite (name -> result)

```typescript
type BenchSuiteResult = { [name: string]: BenchResult };
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L61

### BenchmarkOptions (type)

Options for individual benchmarks

```typescript
interface BenchmarkOptions {
    /** Maximum time to run in seconds (default: 1) */
    maxTime?: number;
    /** Runs before every iteration and is not timed. Async benchmarks only, which then run one iteration at a time. */
    beforeEach?: () => Promise<void>;
    /** Runs after every iteration and is not timed. Async benchmarks only, which then run one iteration at a time. */
    afterEach?: () => Promise<void>;
}
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L66

### BenchSuite (class)

BenchSuite - A benchmark suite for organizing and running multiple benchmarks.

Features:
- Automatic sync/async detection
- Block bar visualization
- Memory tracking
- Relative comparison between benchmarks
- Callback when suite completes

```typescript
export class BenchSuite {
    /**  Global callback when any suite completes */
    static onComplete?: (name: string, result: BenchSuiteResult) => void;
    /**  Name of the benchmark suite */
    constructor(public readonly name: string, private defaultMaxTime: number = , private showSummary: boolean = false);
    /**
     * Add a benchmark to the suite.
     *
     * @param name - Name of the benchmark
     * @param fn - Function to benchmark (can be sync or async)
     * @param options - Optional settings
     */
    add(name: string, fn: () => void | Promise<void>, options: BenchmarkOptions = {}): this;
    /**
     * Run all benchmarks synchronously and return results.
     * Only works with sync benchmark functions.
     * For async benchmarks, use runAsync().
     */
    run(options: {
        verbose?: boolean;
    } = {}): BenchSuiteResult;
    /**
     * Run all benchmarks asynchronously.
     *
     * @returns Promise resolving to suite results
     */
    async runAsync(options: {
        verbose?: boolean;
    } = {}): Promise<BenchSuiteResult>;
    /**
     * Get results as JSON-serializable object.
     */
    getResults(): BenchSuiteResult;
}
```

Source: https://github.com/deepkit/deepkit-framework/blob/master/packages/bench/index.ts#L347
