UNPKG

ghost-performance

Version:

A lightweight Node.js utility that profiles individual function executions with detailed performance metrics

237 lines (180 loc) 6.57 kB
# Ghost Performance A lightweight Node.js (and optionally browser-compatible) utility that profiles individual function executions with detailed performance metrics. ## 📊 What It Does Ghost Performance provides comprehensive profiling for your functions, tracking: - **Best time** - Fastest execution time - **Worst time** - Slowest execution time - **Average time** - Mean execution time - **Standard deviation** - Consistency of performance - **Number of calls** - Total executions tracked - **Estimated memory usage** - Space complexity trend analysis ## 🚀 Installation ```bash npm install ghost-performance ``` ## 📖 Usage ### Basic Function Profiling ```typescript import { profileFunction } from 'ghost-performance'; // Create a profiled version of your function const profiledFunction = profileFunction((n: number) => { // Simulate some work let result = 0; for (let i = 0; i < n; i++) { result += Math.random(); } return result; }); // Use the profiled function normally const result = profiledFunction(1000000); // Get performance metrics const metrics = profiledFunction.getMetrics(); console.log(metrics); // { // calls: 1, // bestTime: 45.23, // worstTime: 45.23, // averageTime: 45.23, // standardDeviation: 0, // totalTime: 45.23, // memoryTrend: { direction: 'stable', rateOfChange: 0, confidence: 0 }, // executionTimes: [45.23], // memorySamples: [] // } // Get a human-readable report console.log(profiledFunction.getReport()); // [GhostProfiler] anonymous Performance Report: // Calls: 1 // Best Time: 45.23ms // Worst Time: 45.23ms // Average Time: 45.23ms // Standard Deviation: 0.00ms // Total Time: 45.23ms ``` ### One-Time Profiling ```typescript import { profileOnce } from 'ghost-performance'; const result = profileOnce( (n: number) => { return Array(n).fill(0).map(() => Math.random()); }, [1000] // arguments ); console.log(result.metrics); console.log(result.result); // The actual function result ``` ### Advanced Profiling with Options ```typescript import { profileFunction } from 'ghost-performance'; const profiledFunction = profileFunction( (data: number[]) => { return data.sort((a, b) => a - b); }, { trackMemory: true, // Enable memory usage tracking maxSamples: 100, // Keep only last 100 samples functionName: 'sort', // Custom function name verbose: true // Log each execution } ); // Run multiple times to see trends for (let i = 0; i < 10; i++) { const data = Array(1000).fill(0).map(() => Math.random()); profiledFunction(data); } // Get detailed metrics const metrics = profiledFunction.getMetrics(); console.log('Memory trend:', metrics.memoryTrend); // Memory trend: { direction: 'stable', rateOfChange: 12.5, confidence: 0.85 } // Reset metrics profiledFunction.reset(); ``` ### Using the Profiler Class Directly ```typescript import { createProfiler } from 'ghost-performance'; const profiler = createProfiler( (n: number) => { return n * n; }, { functionName: 'square', trackMemory: true } ); // Profile multiple executions for (let i = 0; i < 5; i++) { const result = profiler.profile( (n: number) => n * n, [i] ); console.log(`Result: ${result.result}, Time: ${result.metrics.averageTime}ms`); } ``` ## 🔧 API Reference ### `profileFunction<T>(fn: T, options?: ProfilerOptions): ProfiledFunction<T>` Creates a profiled version of a function that tracks performance metrics. **Parameters:** - `fn`: The function to profile - `options`: Optional profiling configuration **Returns:** A profiled function with additional methods: - `getMetrics()`: Get current performance metrics - `reset()`: Reset all metrics - `getReport()`: Get a human-readable performance report ### `profileOnce<T>(fn: (...args: any[]) => T, args?: any[], options?: ProfilerOptions): ProfilerResult<T>` Profiles a single function execution. **Parameters:** - `fn`: The function to profile - `args`: Arguments to pass to the function - `options`: Optional profiling configuration **Returns:** Object containing the function result and performance metrics ### `createProfiler(fn: Function, options?: ProfilerOptions): GhostProfiler` Creates a profiler instance for manual control. ### ProfilerOptions ```typescript interface ProfilerOptions { trackMemory?: boolean; // Enable memory usage tracking (Node.js only) maxSamples?: number; // Maximum samples to keep (default: 1000) functionName?: string; // Custom function name for reporting verbose?: boolean; // Enable detailed logging } ``` ### PerformanceMetrics ```typescript interface PerformanceMetrics { calls: number; // Number of function calls bestTime: number; // Best execution time (ms) worstTime: number; // Worst execution time (ms) averageTime: number; // Average execution time (ms) standardDeviation: number; // Standard deviation (ms) totalTime: number; // Total execution time (ms) memoryTrend: MemoryTrend; // Memory usage trend executionTimes: number[]; // All recorded execution times memorySamples: number[]; // Memory usage samples } ``` ### MemoryTrend ```typescript interface MemoryTrend { direction: 'increasing' | 'decreasing' | 'stable' | 'unknown'; rateOfChange: number; // Bytes per call confidence: number; // Confidence level (0-1) } ``` ## 🌐 Browser Compatibility Ghost Performance works in both Node.js and browser environments: - **Node.js**: Full feature support including memory tracking - **Browser**: Performance tracking only (memory tracking not available) ## 📈 Performance Impact The library is designed to be lightweight with minimal overhead: - **Time overhead**: ~0.01-0.05ms per function call - **Memory overhead**: ~100-200 bytes per profiled function - **CPU overhead**: Negligible for most use cases ## 🤝 Contributing 1. Fork the repository 2. Create a feature branch 3. Make your changes 4. Add tests 5. Submit a pull request ## 📄 License MIT License - see LICENSE file for details. ## 🐛 Issues Found a bug? Please report it on the GitHub issues page. --- **Ghost Performance** - Understand the anatomy of your function's performance. 👻⚡