# Profiling Module Examples

This directory contains Rhai script examples demonstrating the comprehensive system profiling capabilities of the herolib-os profiling module.

## Directory Structure

```
rhaiexamples/profiling/
├── README.md                    # This file
├── 01_system_benchmark.rhai     # Complete system benchmark
├── 02_quick_check.rhai          # Quick performance check
├── 03_stress_test.rhai          # System stress testing
├── 04_report_generation.rhai    # Report generation and export
└── 05_trend_analysis.rhai       # Performance trend analysis
```

## Running Examples

These examples are designed to be run with any Rhai engine that has the herolib-os profiling module registered. 

### Option 1: Using the herolib-os CLI (if available)
```bash
# Run directly with the CLI
herolib-os run rhaiexamples/profiling/01_system_benchmark.rhai
```

### Option 2: Using cargo run with a custom binary
```bash
# If you have a custom binary that uses the herolib-os library
cargo run --bin your-binary -- rhaiexamples/profiling/01_system_benchmark.rhai
```

### Option 3: Programmatic usage
```rust
use herolib_os::rhai::register_profiling_module;
use rhai::Engine;

let mut engine = Engine::new();
register_profiling_module(&mut engine);

// Run the example
engine.run_file("rhaiexamples/profiling/01_system_benchmark.rhai")?;
```

## Example Overview

### 01_system_benchmark.rhai
**Complete System Benchmark**

Comprehensive benchmark that tests all major system components:
- **CPU Performance**: Single-thread, multi-thread scaling, cache performance
- **Memory Performance**: Bandwidth (read/write/copy), latency, NUMA (if available)
- **Disk Performance**: Sequential/random I/O, IOPS, latency
- **Network Performance**: Bandwidth, latency, jitter
- **System Monitoring**: CPU, memory, and I/O utilization

**Runtime**: ~2-5 minutes depending on system performance

### 02_quick_check.rhai
**Quick Performance Check**

Fast performance overview for quick health checks:
- Basic system information
- Single-thread CPU score
- Memory bandwidth (read/write)
- Sequential disk read speed
- Local network latency

**Runtime**: ~30 seconds

### 03_stress_test.rhai
**System Stress Testing**

Intensive stress testing to identify system limits:
- **CPU Stress**: 10-second intensive CPU benchmark
- **Memory Stress**: 25% memory usage stress test
- **Disk Stress**: 10-second disk intensive operations
- **Thermal Check**: Detects thermal throttling
- **Resource Monitoring**: Real-time usage statistics

**Runtime**: ~30-60 seconds

### 04_report_generation.rhai
**Report Generation and Export**

Demonstrates report capabilities:
- Runs benchmarks and creates comprehensive report
- Generates multiple formats (JSON, HTML, Text, CSV)
- Exports reports to files
- Shows report comparison functionality

**Runtime**: ~1-2 minutes

### 05_trend_analysis.rhai
**Performance Trend Analysis**

Advanced trend analysis and monitoring:
- Collects performance data over time
- Generates trend reports and visualizations
- Identifies performance patterns and anomalies
- Compares historical performance data

**Runtime**: ~30 seconds (uses existing data)

## Function Reference

### System Information
```rhai
let profile = SystemProfile();
print(profile.hostname);           // System hostname
print(profile.os_name);           // OS name (linux, macos, windows)
print(profile.os_version);        // OS version
print(profile.cpu_model);         // CPU model
print(profile.cpu_cores);         // Physical cores
print(profile.cpu_threads);       // Logical threads
print(profile.memory_total_bytes); // Total memory in bytes
```

### CPU Profiling
```rhai
// Single-thread performance
let cpu = measure_single_thread_performance();
print(cpu.integer_score);        // Integer operations score
print(cpu.float_score);          // Floating-point operations score
print(cpu.combined_score);       // Combined score

// Multi-thread scaling
let scaling = measure_multi_thread_scaling(threads);
print(scaling.speedup);           // Actual speedup
print(scaling.ideal_speedup);    // Theoretical speedup
print(scaling.scaling_efficiency); // Efficiency percentage

// Cache performance
let cache = measure_cache_misses();
print(cache.l1_miss_rate);        // L1 cache miss rate
print(cache.l2_miss_rate);        // L2 cache miss rate
print(cache.l3_miss_rate);        // L3 cache miss rate

// Instruction throughput
let instr = test_instruction_throughput();
print(instr.integer_ops_per_sec);  // Integer ops/sec
print(instr.float_ops_per_sec);    // Float ops/sec
```

### Memory Profiling
```rhai
// Memory bandwidth
let mem = measure_memory_bandwidth();
print(mem.read_bandwidth_gbps);    // Read bandwidth in GB/s
print(mem.write_bandwidth_gbps);   // Write bandwidth in GB/s
print(mem.copy_bandwidth_gbps);    // Copy bandwidth in GB/s

// Memory latency
let latency = test_memory_latency();
print(latency.avg_ns);            // Average latency in nanoseconds

// NUMA bandwidth (if available)
let numa = test_numa_bandwidth();
print(numa.local_bandwidth_gbps);  // Local memory bandwidth
print(numa.remote_bandwidth_gbps); // Remote memory bandwidth

// Memory stress testing
let stress = run_memory_stress_test(seconds, memory_bytes);
print(stress.peak_read_bandwidth_gbps);
print(stress.peak_write_bandwidth_gbps);
print(stress.error_count);         // Memory errors detected
```

### Disk Profiling
```rhai
// Sequential performance
let seq_read = measure_sequential_read(path, size_bytes);
let seq_write = measure_sequential_write(path, size_bytes);
print(seq_read.throughput_mbps);   // MB/s
print(seq_write.throughput_mbps);  // MB/s

// Random performance
let rand_read = measure_random_read(path, size_bytes, block_size);
let rand_write = measure_random_write(path, size_bytes, block_size);
print(rand_read.throughput_mbps);  // MB/s
print(rand_write.throughput_mbps); // MB/s

// IOPS performance
let iops = measure_iops(path, size_bytes, block_size);
print(iops.read_iops);             // Read operations per second
print(iops.write_iops);            // Write operations per second

// Disk latency
let latency = test_disk_latency(path);
print(latency.avg_us);             // Average latency in microseconds

// Complete disk benchmark
let disk = run_disk_benchmark(path, seconds);
print(disk.sequential_read.throughput_mbps);
print(disk.random_write.throughput_mbps);
print(disk.iops.read_iops);
```

### Network Profiling
```rhai
// Bandwidth measurement
let bandwidth = measure_bandwidth(host, seconds);
print(bandwidth.upload_bps);      // Upload bits per second
print(bandwidth.download_bps);     // Download bits per second

// Latency measurement
let latency = measure_latency(host, count);
print(latency.min_ms);            // Minimum latency in ms
print(latency.max_ms);            // Maximum latency in ms
print(latency.avg_ms);            // Average latency in ms
print(latency.stddev_ms);         // Standard deviation

// Jitter measurement
let jitter = run_jitter_test(host);
print(jitter.jitter_ms);           // Jitter in milliseconds

// UDP throughput
let udp = test_udp_throughput(host, target_bandwidth);
print(udp.actual_bandwidth_bps);   // Actual bandwidth achieved
print(udp.packet_loss_percent);    // Packet loss percentage
```

### System Monitoring
```rhai
// CPU utilization
let cpu_usage = sample_cpu_utilization();
print(cpu_usage * 100);            // CPU usage percentage

// Memory usage
let mem_usage = sample_memory_usage();
print(mem_usage.usage_percent * 100); // Memory usage percentage
print(mem_usage.available_bytes);      // Available bytes

// I/O statistics
let io_stats = sample_io_statistics();
print(io_stats.read_iops);         // Read IOPS
print(io_stats.write_iops);        // Write IOPS

// Thermal throttling detection
let throttling = detect_thermal_throttling();
if throttling {
    print("System is thermal throttling!");
}
```

### Report Generation
```rhai
// Create report with metadata
let report = BenchmarkReport();
report.set_system_profile(SystemProfile());
report.set_environment("production");     // Set environment
report.set_git_commit("abc123");          // Set version/commit
report.add_tag("region", "us-east-1");    // Add custom tags
report.add_tag("cluster", "prod-01");

// Automatic fields
print(report.benchmark_id);               // Auto-generated UUID
print(report.timestamp);                  // Auto-generated timestamp

// Add results
report.add_cpu_result(cpu_result);
report.add_memory_result(mem_result);
report.add_disk_result(disk_result);
report.add_network_result(net_result);

// Generate formats
let json = report.generate_json();
let html = report.generate_html();
let text = report.generate_text();

// Save/load reports
report.save_report_file("/path/to/report.json");
let loaded = load_report_file("/path/to/report.json");

// Export to CSV
report.export_to_csv("/path/to/report.csv");

// Compare with baseline
let comparison = compare_reports(report, baseline_report);
print(comparison.cpu_delta_percent);      // CPU delta percentage
print(comparison.regressions);            // List of regressions
print(comparison.improvements);           // List of improvements
```

### Trend Analysis (NEW)
```rhai
// Load multiple historical reports
let reports = [];
reports.push(load_report_file("/history/report1.json"));
reports.push(load_report_file("/history/report2.json"));
reports.push(load_report_file("/history/report3.json"));

// Analyze performance trend
let trend = analyze_trend(reports, "cpu");
print(trend.direction);                   // Improving/Degrading/Stable/Volatile
print(trend.mean);                        // Mean value
print(trend.stddev);                      // Standard deviation
print(trend.slope);                       // Linear regression slope
print(trend.min);                         // Minimum value
print(trend.max);                         // Maximum value
print(trend.sample_count);                // Number of samples

// Detect regressions (5% threshold)
let regressions = detect_regressions(reports, 5.0);
for regression in regressions {
    print(regression.metric);             // cpu/memory/disk/network
    print(regression.timestamp);          // When regression occurred
    print(regression.delta_percent);      // Performance degradation %
    print(regression.severity);           // Minor/Moderate/Severe/Critical
}

// Calculate statistics
let stats = calculate_statistics(reports);
print(stats.cpu_mean);                    // CPU mean across all reports
print(stats.cpu_stddev);                  // CPU standard deviation
print(stats.memory_mean);                 // Memory mean
print(stats.sample_count);                // Total samples
```

## Performance Tips

1. **Quick Checks**: Use `02_quick_check.rhai` for fast health checks
2. **Full Benchmarks**: Use `01_system_benchmark.rhai` for comprehensive analysis
3. **Stress Testing**: Use `03_stress_test.rhai` to identify system limits
4. **Report Generation**: Use `04_report_generation.rhai` for documentation and comparison

## Notes

- Some tests require sufficient disk space in `/tmp` directory
- Network tests use localhost for safe demonstration
- Stress tests are intensive but safe for production systems
- Reports are exported to `/tmp/` by default
- All examples include error handling and progress reporting

## Security

All profiling operations are sandboxed and safe:
- No privileged operations required
- Temporary files created with secure permissions
- Resource limits enforced to prevent system overload
- Input validation prevents malicious operations
