Files
hakmem/core/hakmem_p2.h

47 lines
1.5 KiB
C
Raw Normal View History

// hakmem_p2.h - P² (P-square) Algorithm for Percentile Estimation
// Purpose: O(1) memory, O(1) update, 1-2% accuracy for p99 estimation
//
// Reference: Jain & Chlamtac (1985) "The P² algorithm for dynamic
// calculation of quantiles and histograms without storing observations"
//
// License: MIT
// Date: 2025-10-21
#ifndef HAKMEM_P2_H
#define HAKMEM_P2_H
#include <stdint.h>
// ============================================================================
// P² Estimator (5 markers: min, p25, p50, p75, p99)
// ============================================================================
typedef struct {
double q[5]; // Marker heights (quantile values)
int n[5]; // Marker positions (1-based indices)
double dn[5]; // Desired marker positions (increments)
int count; // Total samples processed
double target_p; // Target percentile (0.99 for p99)
} hak_p2_t;
// ============================================================================
// Public API
// ============================================================================
// Initialize P² estimator for target percentile (e.g., 0.99 for p99)
void hak_p2_init(hak_p2_t* p2, double target_p);
// Add a new sample value
void hak_p2_add(hak_p2_t* p2, double value);
// Get current percentile estimate
double hak_p2_get(hak_p2_t* p2);
// Reset estimator (start new window)
void hak_p2_reset(hak_p2_t* p2);
// Get sample count
int hak_p2_count(hak_p2_t* p2);
#endif // HAKMEM_P2_H