@fuzdev/fuz_util 0.42.0 → 0.43.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (46) hide show
  1. package/LICENSE +1 -1
  2. package/README.md +19 -12
  3. package/dist/async.d.ts +2 -2
  4. package/dist/async.d.ts.map +1 -1
  5. package/dist/async.js +2 -2
  6. package/dist/benchmark.d.ts +179 -0
  7. package/dist/benchmark.d.ts.map +1 -0
  8. package/dist/benchmark.js +400 -0
  9. package/dist/benchmark_baseline.d.ts +195 -0
  10. package/dist/benchmark_baseline.d.ts.map +1 -0
  11. package/dist/benchmark_baseline.js +415 -0
  12. package/dist/benchmark_format.d.ts +92 -0
  13. package/dist/benchmark_format.d.ts.map +1 -0
  14. package/dist/benchmark_format.js +327 -0
  15. package/dist/benchmark_stats.d.ts +112 -0
  16. package/dist/benchmark_stats.d.ts.map +1 -0
  17. package/dist/benchmark_stats.js +336 -0
  18. package/dist/benchmark_types.d.ts +174 -0
  19. package/dist/benchmark_types.d.ts.map +1 -0
  20. package/dist/benchmark_types.js +1 -0
  21. package/dist/library_json.d.ts +3 -3
  22. package/dist/library_json.d.ts.map +1 -1
  23. package/dist/library_json.js +1 -1
  24. package/dist/object.js +1 -1
  25. package/dist/stats.d.ts +126 -0
  26. package/dist/stats.d.ts.map +1 -0
  27. package/dist/stats.js +262 -0
  28. package/dist/time.d.ts +161 -0
  29. package/dist/time.d.ts.map +1 -0
  30. package/dist/time.js +260 -0
  31. package/dist/timings.d.ts +1 -7
  32. package/dist/timings.d.ts.map +1 -1
  33. package/dist/timings.js +16 -16
  34. package/package.json +21 -19
  35. package/src/lib/async.ts +3 -3
  36. package/src/lib/benchmark.ts +498 -0
  37. package/src/lib/benchmark_baseline.ts +573 -0
  38. package/src/lib/benchmark_format.ts +379 -0
  39. package/src/lib/benchmark_stats.ts +448 -0
  40. package/src/lib/benchmark_types.ts +197 -0
  41. package/src/lib/library_json.ts +3 -3
  42. package/src/lib/object.ts +1 -1
  43. package/src/lib/stats.ts +353 -0
  44. package/src/lib/time.ts +314 -0
  45. package/src/lib/timings.ts +17 -17
  46. package/src/lib/types.ts +2 -2
@@ -0,0 +1,126 @@
1
+ /**
2
+ * Statistical analysis utilities.
3
+ * Pure functions with zero dependencies - can be used standalone for any data analysis.
4
+ */
5
+ /**
6
+ * Calculate the mean (average) of an array of numbers.
7
+ */
8
+ export declare const stats_mean: (values: Array<number>) => number;
9
+ /**
10
+ * Calculate the median of an array of numbers.
11
+ */
12
+ export declare const stats_median: (values: Array<number>) => number;
13
+ /**
14
+ * Calculate the standard deviation of an array of numbers.
15
+ * Uses population standard deviation (divides by n, not n-1).
16
+ * For benchmarks with many samples, this is typically appropriate.
17
+ */
18
+ export declare const stats_std_dev: (values: Array<number>, mean?: number) => number;
19
+ /**
20
+ * Calculate the variance of an array of numbers.
21
+ */
22
+ export declare const stats_variance: (values: Array<number>, mean?: number) => number;
23
+ /**
24
+ * Calculate a percentile of an array of numbers using linear interpolation.
25
+ * Uses the "R-7" method (default in R, NumPy, Excel) which interpolates between
26
+ * data points for more accurate percentile estimates, especially with smaller samples.
27
+ * @param values - Array of numbers
28
+ * @param p - Percentile (0-1, e.g., 0.95 for 95th percentile)
29
+ */
30
+ export declare const stats_percentile: (values: Array<number>, p: number) => number;
31
+ /**
32
+ * Calculate the coefficient of variation (CV).
33
+ * CV = standard deviation / mean, expressed as a ratio.
34
+ * Useful for comparing relative variability between datasets.
35
+ */
36
+ export declare const stats_cv: (mean: number, std_dev: number) => number;
37
+ /**
38
+ * Calculate min and max values.
39
+ */
40
+ export declare const stats_min_max: (values: Array<number>) => {
41
+ min: number;
42
+ max: number;
43
+ };
44
+ /**
45
+ * Result from outlier detection.
46
+ */
47
+ export interface StatsOutlierResult {
48
+ /** Values after removing outliers */
49
+ cleaned: Array<number>;
50
+ /** Detected outlier values */
51
+ outliers: Array<number>;
52
+ }
53
+ /**
54
+ * Configuration options for IQR outlier detection.
55
+ */
56
+ export interface StatsOutliersIqrOptions {
57
+ /** Multiplier for IQR bounds (default: 1.5) */
58
+ iqr_multiplier?: number;
59
+ /** Minimum sample size to perform outlier detection (default: 3) */
60
+ min_sample_size?: number;
61
+ }
62
+ /**
63
+ * Detect outliers using the IQR (Interquartile Range) method.
64
+ * Values outside [Q1 - multiplier*IQR, Q3 + multiplier*IQR] are considered outliers.
65
+ */
66
+ export declare const stats_outliers_iqr: (values: Array<number>, options?: StatsOutliersIqrOptions) => StatsOutlierResult;
67
+ /**
68
+ * Configuration options for MAD outlier detection.
69
+ */
70
+ export interface StatsOutliersMadOptions {
71
+ /** Modified Z-score threshold for outlier detection (default: 3.5) */
72
+ z_score_threshold?: number;
73
+ /** Extreme Z-score threshold when too many outliers detected (default: 5.0) */
74
+ z_score_extreme?: number;
75
+ /** MAD constant for normal distribution (default: 0.6745) */
76
+ mad_constant?: number;
77
+ /** Ratio threshold to switch to extreme mode (default: 0.3) */
78
+ outlier_ratio_high?: number;
79
+ /** Ratio threshold to switch to keep-closest mode (default: 0.4) */
80
+ outlier_ratio_extreme?: number;
81
+ /** Ratio of values to keep in keep-closest mode (default: 0.8) */
82
+ outlier_keep_ratio?: number;
83
+ /** Minimum sample size to perform outlier detection (default: 3) */
84
+ min_sample_size?: number;
85
+ /** Options to pass to IQR fallback when MAD is zero */
86
+ iqr_options?: StatsOutliersIqrOptions;
87
+ }
88
+ /**
89
+ * Detect outliers using the MAD (Median Absolute Deviation) method.
90
+ * More robust than IQR for skewed distributions.
91
+ * Uses modified Z-score: |0.6745 * (x - median) / MAD|
92
+ * Values with modified Z-score > threshold are considered outliers.
93
+ */
94
+ export declare const stats_outliers_mad: (values: Array<number>, options?: StatsOutliersMadOptions) => StatsOutlierResult;
95
+ /**
96
+ * Common z-scores for confidence intervals.
97
+ */
98
+ export declare const CONFIDENCE_Z_SCORES: Record<number, number>;
99
+ /**
100
+ * Convert a confidence level (0-1) to a z-score.
101
+ * Uses a lookup table for common values, approximates others.
102
+ *
103
+ * @example
104
+ * ```ts
105
+ * confidence_level_to_z_score(0.95); // 1.96
106
+ * confidence_level_to_z_score(0.99); // 2.576
107
+ * ```
108
+ */
109
+ export declare const confidence_level_to_z_score: (level: number) => number;
110
+ /**
111
+ * Configuration options for confidence interval calculation.
112
+ */
113
+ export interface StatsConfidenceIntervalOptions {
114
+ /** Z-score for confidence level (default: 1.96 for 95% CI) */
115
+ z_score?: number;
116
+ /** Confidence level (0-1), alternative to z_score. If both provided, z_score takes precedence. */
117
+ confidence_level?: number;
118
+ }
119
+ /**
120
+ * Calculate confidence interval for the mean.
121
+ * @param values - Array of numbers
122
+ * @param options - Configuration options
123
+ * @returns [lower_bound, upper_bound]
124
+ */
125
+ export declare const stats_confidence_interval: (values: Array<number>, options?: StatsConfidenceIntervalOptions) => [number, number];
126
+ //# sourceMappingURL=stats.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"stats.d.ts","sourceRoot":"../src/lib/","sources":["../src/lib/stats.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAaH;;GAEG;AACH,eAAO,MAAM,UAAU,GAAI,QAAQ,KAAK,CAAC,MAAM,CAAC,KAAG,MAGlD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,YAAY,GAAI,QAAQ,KAAK,CAAC,MAAM,CAAC,KAAG,MAKpD,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,aAAa,GAAI,QAAQ,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,MAAM,KAAG,MAKpE,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,cAAc,GAAI,QAAQ,KAAK,CAAC,MAAM,CAAC,EAAE,OAAO,MAAM,KAAG,MAIrE,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,gBAAgB,GAAI,QAAQ,KAAK,CAAC,MAAM,CAAC,EAAE,GAAG,MAAM,KAAG,MAmBnE,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,QAAQ,GAAI,MAAM,MAAM,EAAE,SAAS,M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M,mBAAmB,EAAE,MAAM,CAAC,MAAM,EAAE,MAAM,CAMtD,CAAC;AAEF;;;;;;;;;GASG;AACH,eAAO,MAAM,2BAA2B,GAAI,OAAO,MAAM,KAAG,MAuB3D,CAAC;AAEF;;GAEG;AACH,MAAM,WAAW,8BAA8B;IAC9C,8DAA8D;IAC9D,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,kGAAkG;IAClG,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC1B;AAED;;;;;GAKG;AACH,eAAO,MAAM,yBAAyB,GACrC,QAAQ,KAAK,CAAC,MAAM,CAAC,EACrB,UAAU,8BAA8B,KACtC,CAAC,MAAM,EAAE,MAAM,CAgBjB,CAAC"}
package/dist/stats.js ADDED
@@ -0,0 +1,262 @@
1
+ /**
2
+ * Statistical analysis utilities.
3
+ * Pure functions with zero dependencies - can be used standalone for any data analysis.
4
+ */
5
+ // Statistical constants (defaults)
6
+ const DEFAULT_IQR_MULTIPLIER = 1.5;
7
+ const DEFAULT_MAD_Z_SCORE_THRESHOLD = 3.5;
8
+ const DEFAULT_MAD_Z_SCORE_EXTREME = 5.0;
9
+ const DEFAULT_MAD_CONSTANT = 0.6745; // For normal distribution approximation
10
+ const DEFAULT_OUTLIER_RATIO_HIGH = 0.3;
11
+ const DEFAULT_OUTLIER_RATIO_EXTREME = 0.4;
12
+ const DEFAULT_OUTLIER_KEEP_RATIO = 0.8;
13
+ const DEFAULT_CONFIDENCE_Z = 1.96; // 95% confidence
14
+ const DEFAULT_MIN_SAMPLE_SIZE = 3;
15
+ /**
16
+ * Calculate the mean (average) of an array of numbers.
17
+ */
18
+ export const stats_mean = (values) => {
19
+ if (values.length === 0)
20
+ return NaN;
21
+ return values.reduce((sum, val) => sum + val, 0) / values.length;
22
+ };
23
+ /**
24
+ * Calculate the median of an array of numbers.
25
+ */
26
+ export const stats_median = (values) => {
27
+ if (values.length === 0)
28
+ return NaN;
29
+ const sorted = [...values].sort((a, b) => a - b);
30
+ const mid = Math.floor(sorted.length / 2);
31
+ return sorted.length % 2 === 0 ? (sorted[mid - 1] + sorted[mid]) / 2 : sorted[mid];
32
+ };
33
+ /**
34
+ * Calculate the standard deviation of an array of numbers.
35
+ * Uses population standard deviation (divides by n, not n-1).
36
+ * For benchmarks with many samples, this is typically appropriate.
37
+ */
38
+ export const stats_std_dev = (values, mean) => {
39
+ if (values.length === 0)
40
+ return NaN;
41
+ const m = mean ?? stats_mean(values);
42
+ const variance = values.reduce((sum, val) => sum + (val - m) ** 2, 0) / values.length;
43
+ return Math.sqrt(variance);
44
+ };
45
+ /**
46
+ * Calculate the variance of an array of numbers.
47
+ */
48
+ export const stats_variance = (values, mean) => {
49
+ if (values.length === 0)
50
+ return NaN;
51
+ const m = mean ?? stats_mean(values);
52
+ return values.reduce((sum, val) => sum + (val - m) ** 2, 0) / values.length;
53
+ };
54
+ /**
55
+ * Calculate a percentile of an array of numbers using linear interpolation.
56
+ * Uses the "R-7" method (default in R, NumPy, Excel) which interpolates between
57
+ * data points for more accurate percentile estimates, especially with smaller samples.
58
+ * @param values - Array of numbers
59
+ * @param p - Percentile (0-1, e.g., 0.95 for 95th percentile)
60
+ */
61
+ export const stats_percentile = (values, p) => {
62
+ if (values.length === 0)
63
+ return NaN;
64
+ if (values.length === 1)
65
+ return values[0];
66
+ const sorted = [...values].sort((a, b) => a - b);
67
+ const n = sorted.length;
68
+ // R-7 method: index = (n - 1) * p
69
+ const index = (n - 1) * p;
70
+ const lower = Math.floor(index);
71
+ const upper = Math.ceil(index);
72
+ if (lower === upper) {
73
+ return sorted[lower];
74
+ }
75
+ // Linear interpolation between the two nearest values
76
+ const fraction = index - lower;
77
+ return sorted[lower] + fraction * (sorted[upper] - sorted[lower]);
78
+ };
79
+ /**
80
+ * Calculate the coefficient of variation (CV).
81
+ * CV = standard deviation / mean, expressed as a ratio.
82
+ * Useful for comparing relative variability between datasets.
83
+ */
84
+ export const stats_cv = (mean, std_dev) => {
85
+ if (mean === 0)
86
+ return NaN;
87
+ return std_dev / mean;
88
+ };
89
+ /**
90
+ * Calculate min and max values.
91
+ */
92
+ export const stats_min_max = (values) => {
93
+ if (values.length === 0)
94
+ return { min: NaN, max: NaN };
95
+ let min = values[0];
96
+ let max = values[0];
97
+ for (let i = 1; i < values.length; i++) {
98
+ const val = values[i];
99
+ if (val < min)
100
+ min = val;
101
+ if (val > max)
102
+ max = val;
103
+ }
104
+ return { min, max };
105
+ };
106
+ /**
107
+ * Detect outliers using the IQR (Interquartile Range) method.
108
+ * Values outside [Q1 - multiplier*IQR, Q3 + multiplier*IQR] are considered outliers.
109
+ */
110
+ export const stats_outliers_iqr = (values, options) => {
111
+ const iqr_multiplier = options?.iqr_multiplier ?? DEFAULT_IQR_MULTIPLIER;
112
+ const min_sample_size = options?.min_sample_size ?? DEFAULT_MIN_SAMPLE_SIZE;
113
+ if (values.length < min_sample_size) {
114
+ return { cleaned: values, outliers: [] };
115
+ }
116
+ const sorted = [...values].sort((a, b) => a - b);
117
+ const q1 = sorted[Math.floor(sorted.length * 0.25)];
118
+ const q3 = sorted[Math.floor(sorted.length * 0.75)];
119
+ const iqr = q3 - q1;
120
+ if (iqr === 0) {
121
+ return { cleaned: values, outliers: [] };
122
+ }
123
+ const lower_bound = q1 - iqr_multiplier * iqr;
124
+ const upper_bound = q3 + iqr_multiplier * iqr;
125
+ const cleaned = [];
126
+ const outliers = [];
127
+ for (const value of values) {
128
+ if (value < lower_bound || value > upper_bound) {
129
+ outliers.push(value);
130
+ }
131
+ else {
132
+ cleaned.push(value);
133
+ }
134
+ }
135
+ return { cleaned, outliers };
136
+ };
137
+ /**
138
+ * Detect outliers using the MAD (Median Absolute Deviation) method.
139
+ * More robust than IQR for skewed distributions.
140
+ * Uses modified Z-score: |0.6745 * (x - median) / MAD|
141
+ * Values with modified Z-score > threshold are considered outliers.
142
+ */
143
+ export const stats_outliers_mad = (values, options) => {
144
+ const z_score_threshold = options?.z_score_threshold ?? DEFAULT_MAD_Z_SCORE_THRESHOLD;
145
+ const z_score_extreme = options?.z_score_extreme ?? DEFAULT_MAD_Z_SCORE_EXTREME;
146
+ const mad_constant = options?.mad_constant ?? DEFAULT_MAD_CONSTANT;
147
+ const outlier_ratio_high = options?.outlier_ratio_high ?? DEFAULT_OUTLIER_RATIO_HIGH;
148
+ const outlier_ratio_extreme = options?.outlier_ratio_extreme ?? DEFAULT_OUTLIER_RATIO_EXTREME;
149
+ const outlier_keep_ratio = options?.outlier_keep_ratio ?? DEFAULT_OUTLIER_KEEP_RATIO;
150
+ const min_sample_size = options?.min_sample_size ?? DEFAULT_MIN_SAMPLE_SIZE;
151
+ const iqr_options = options?.iqr_options;
152
+ if (values.length < min_sample_size) {
153
+ return { cleaned: values, outliers: [] };
154
+ }
155
+ const sorted = [...values].sort((a, b) => a - b);
156
+ const median = stats_median(sorted);
157
+ // Calculate MAD (Median Absolute Deviation)
158
+ const deviations = values.map((v) => Math.abs(v - median));
159
+ const sorted_deviations = [...deviations].sort((a, b) => a - b);
160
+ const mad = stats_median(sorted_deviations);
161
+ // If MAD is zero, fall back to IQR method
162
+ if (mad === 0) {
163
+ return stats_outliers_iqr(values, iqr_options);
164
+ }
165
+ // Use modified Z-score with MAD
166
+ let cleaned = [];
167
+ let outliers = [];
168
+ for (const value of values) {
169
+ const modified_z_score = (mad_constant * (value - median)) / mad;
170
+ if (Math.abs(modified_z_score) > z_score_threshold) {
171
+ outliers.push(value);
172
+ }
173
+ else {
174
+ cleaned.push(value);
175
+ }
176
+ }
177
+ // If too many outliers, increase threshold and try again
178
+ if (outliers.length > values.length * outlier_ratio_high) {
179
+ cleaned = [];
180
+ outliers = [];
181
+ for (const value of values) {
182
+ const modified_z_score = (mad_constant * (value - median)) / mad;
183
+ if (Math.abs(modified_z_score) > z_score_extreme) {
184
+ outliers.push(value);
185
+ }
186
+ else {
187
+ cleaned.push(value);
188
+ }
189
+ }
190
+ // If still too many outliers, keep closest values to median
191
+ if (outliers.length > values.length * outlier_ratio_extreme) {
192
+ const with_distances = values.map((v) => ({
193
+ value: v,
194
+ distance: Math.abs(v - median),
195
+ }));
196
+ with_distances.sort((a, b) => a.distance - b.distance);
197
+ const keep_count = Math.floor(values.length * outlier_keep_ratio);
198
+ cleaned = with_distances.slice(0, keep_count).map((d) => d.value);
199
+ outliers = with_distances.slice(keep_count).map((d) => d.value);
200
+ }
201
+ }
202
+ return { cleaned, outliers };
203
+ };
204
+ /**
205
+ * Common z-scores for confidence intervals.
206
+ */
207
+ export const CONFIDENCE_Z_SCORES = {
208
+ 0.8: 1.282,
209
+ 0.9: 1.645,
210
+ 0.95: 1.96,
211
+ 0.99: 2.576,
212
+ 0.999: 3.291,
213
+ };
214
+ /**
215
+ * Convert a confidence level (0-1) to a z-score.
216
+ * Uses a lookup table for common values, approximates others.
217
+ *
218
+ * @example
219
+ * ```ts
220
+ * confidence_level_to_z_score(0.95); // 1.96
221
+ * confidence_level_to_z_score(0.99); // 2.576
222
+ * ```
223
+ */
224
+ export const confidence_level_to_z_score = (level) => {
225
+ if (level <= 0 || level >= 1) {
226
+ throw new Error('Confidence level must be between 0 and 1 (exclusive)');
227
+ }
228
+ // Check lookup table first
229
+ if (level in CONFIDENCE_Z_SCORES) {
230
+ return CONFIDENCE_Z_SCORES[level];
231
+ }
232
+ // For confidence level c, we want z such that P(-z < Z < z) = c
233
+ // This means Φ(z) = (1 + c) / 2, so z = Φ⁻¹((1 + c) / 2)
234
+ // Using Φ⁻¹(p) = √2 * erfinv(2p - 1)
235
+ const p = (1 + level) / 2; // e.g., 0.95 -> 0.975
236
+ const x = 2 * p - 1; // Argument for erfinv, e.g., 0.975 -> 0.95
237
+ // Winitzki approximation for erfinv
238
+ const a = 0.147;
239
+ const ln_term = Math.log(1 - x * x);
240
+ const term1 = 2 / (Math.PI * a) + ln_term / 2;
241
+ const erfinv = Math.sign(x) * Math.sqrt(Math.sqrt(term1 * term1 - ln_term / a) - term1);
242
+ return Math.SQRT2 * erfinv;
243
+ };
244
+ /**
245
+ * Calculate confidence interval for the mean.
246
+ * @param values - Array of numbers
247
+ * @param options - Configuration options
248
+ * @returns [lower_bound, upper_bound]
249
+ */
250
+ export const stats_confidence_interval = (values, options) => {
251
+ // z_score takes precedence, then confidence_level, then default
252
+ const z_score = options?.z_score ??
253
+ (options?.confidence_level ? confidence_level_to_z_score(options.confidence_level) : null) ??
254
+ DEFAULT_CONFIDENCE_Z;
255
+ if (values.length === 0)
256
+ return [NaN, NaN];
257
+ const mean = stats_mean(values);
258
+ const std_dev = stats_std_dev(values, mean);
259
+ const se = std_dev / Math.sqrt(values.length);
260
+ const margin = z_score * se;
261
+ return [mean - margin, mean + margin];
262
+ };
package/dist/time.d.ts ADDED
@@ -0,0 +1,161 @@
1
+ /**
2
+ * Time utilities.
3
+ * Provides cross-platform high-resolution timing and measurement helpers.
4
+ */
5
+ /**
6
+ * Timer interface for measuring elapsed time.
7
+ * Returns time in nanoseconds for maximum precision.
8
+ */
9
+ export interface Timer {
10
+ /** Get current time in nanoseconds */
11
+ now: () => number;
12
+ }
13
+ /**
14
+ * Node.js high-resolution timer using process.hrtime.bigint().
15
+ * Provides true nanosecond precision.
16
+ */
17
+ export declare const timer_node: Timer;
18
+ /**
19
+ * Browser high-resolution timer using performance.now().
20
+ * Converts milliseconds to nanoseconds for consistent API.
21
+ *
22
+ * **Precision varies by browser due to Spectre/Meltdown mitigations:**
23
+ * - Chrome: ~100μs (coarsened)
24
+ * - Firefox: ~1ms (rounded)
25
+ * - Safari: ~100μs
26
+ * - Node.js: ~1μs
27
+ *
28
+ * For nanosecond-precision benchmarks, use Node.js with `timer_node`.
29
+ */
30
+ export declare const timer_browser: Timer;
31
+ /**
32
+ * Auto-detected timer based on environment.
33
+ * Uses process.hrtime in Node.js, performance.now() in browsers.
34
+ * The timer function is detected once and cached for performance.
35
+ */
36
+ export declare const timer_default: Timer;
37
+ /**
38
+ * Time units and conversions.
39
+ */
40
+ export declare const TIME_NS_PER_US = 1000;
41
+ export declare const TIME_NS_PER_MS = 1000000;
42
+ export declare const TIME_NS_PER_SEC = 1000000000;
43
+ /**
44
+ * Convert nanoseconds to microseconds.
45
+ */
46
+ export declare const time_ns_to_us: (ns: number) => number;
47
+ /**
48
+ * Convert nanoseconds to milliseconds.
49
+ */
50
+ export declare const time_ns_to_ms: (ns: number) => number;
51
+ /**
52
+ * Convert nanoseconds to seconds.
53
+ */
54
+ export declare const time_ns_to_sec: (ns: number) => number;
55
+ /**
56
+ * Time unit for formatting.
57
+ */
58
+ export type TimeUnit = 'ns' | 'us' | 'ms' | 's';
59
+ /**
60
+ * Detect the best time unit for a set of nanosecond values.
61
+ * Chooses the unit where most values fall in the range 1-9999.
62
+ * @param values_ns - Array of times in nanoseconds
63
+ * @returns Best unit to use for all values
64
+ */
65
+ export declare const time_unit_detect_best: (values_ns: Array<number>) => TimeUnit;
66
+ /**
67
+ * Format time with a specific unit.
68
+ * @param ns - Time in nanoseconds
69
+ * @param unit - Unit to use ('ns', 'us', 'ms', 's')
70
+ * @param decimals - Number of decimal places (default: 2)
71
+ * @returns Formatted string like "3.87μs"
72
+ */
73
+ export declare const time_format: (ns: number, unit: TimeUnit, decimals?: number) => string;
74
+ /**
75
+ * Format time with adaptive units (ns/μs/ms/s) based on magnitude.
76
+ * @param ns - Time in nanoseconds
77
+ * @param decimals - Number of decimal places (default: 2)
78
+ * @returns Formatted string like "3.87μs" or "1.23ms"
79
+ *
80
+ * @example
81
+ * ```ts
82
+ * time_format_adaptive(1500) // "1.50μs"
83
+ * time_format_adaptive(3870) // "3.87μs"
84
+ * time_format_adaptive(1500000) // "1.50ms"
85
+ * time_format_adaptive(1500000000) // "1.50s"
86
+ * ```
87
+ */
88
+ export declare const time_format_adaptive: (ns: number, decimals?: number) => string;
89
+ /**
90
+ * Result from timing a function execution.
91
+ * All times in nanoseconds for maximum precision.
92
+ */
93
+ export interface TimeResult {
94
+ /** Elapsed time in nanoseconds */
95
+ elapsed_ns: number;
96
+ /** Elapsed time in microseconds (convenience) */
97
+ elapsed_us: number;
98
+ /** Elapsed time in milliseconds (convenience) */
99
+ elapsed_ms: number;
100
+ /** Start time in nanoseconds (from timer.now()) */
101
+ started_at_ns: number;
102
+ /** End time in nanoseconds (from timer.now()) */
103
+ ended_at_ns: number;
104
+ }
105
+ /**
106
+ * Time an asynchronous function execution.
107
+ * @param fn - Async function to time
108
+ * @param timer - Timer to use (defaults to timer_default)
109
+ * @returns Object containing the function result and timing information
110
+ *
111
+ * @example
112
+ * ```ts
113
+ * const {result, timing} = await time_async(async () => {
114
+ * await fetch('https://api.example.com/data');
115
+ * return 42;
116
+ * });
117
+ * console.log(`Result: ${result}, took ${time_format_adaptive(timing.elapsed_ns)}`);
118
+ * ```
119
+ */
120
+ export declare const time_async: <T>(fn: () => Promise<T>, timer?: Timer) => Promise<{
121
+ result: T;
122
+ timing: TimeResult;
123
+ }>;
124
+ /**
125
+ * Time a synchronous function execution.
126
+ * @param fn - Sync function to time
127
+ * @param timer - Timer to use (defaults to timer_default)
128
+ * @returns Object containing the function result and timing information
129
+ *
130
+ * @example
131
+ * ```ts
132
+ * const {result, timing} = time_sync(() => {
133
+ * return expensive_computation();
134
+ * });
135
+ * console.log(`Result: ${result}, took ${time_format_adaptive(timing.elapsed_ns)}`);
136
+ * ```
137
+ */
138
+ export declare const time_sync: <T>(fn: () => T, timer?: Timer) => {
139
+ result: T;
140
+ timing: TimeResult;
141
+ };
142
+ /**
143
+ * Measure multiple executions of a function and return all timings.
144
+ * @param fn - Function to measure (sync or async)
145
+ * @param iterations - Number of times to execute
146
+ * @param timer - Timer to use (defaults to timer_default)
147
+ * @returns Array of elapsed times in nanoseconds
148
+ *
149
+ * @example
150
+ * ```ts
151
+ * const timings_ns = await time_measure(async () => {
152
+ * await process_data();
153
+ * }, 100);
154
+ *
155
+ * import {BenchmarkStats} from './benchmark_stats.js';
156
+ * const stats = new BenchmarkStats(timings_ns);
157
+ * console.log(`Mean: ${time_format_adaptive(stats.mean_ns)}`);
158
+ * ```
159
+ */
160
+ export declare const time_measure: (fn: () => unknown, iterations: number, timer?: Timer) => Promise<Array<number>>;
161
+ //# sourceMappingURL=time.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"time.d.ts","sourceRoot":"../src/lib/","sources":["../src/lib/time.ts"],"names":[],"mappings":"AAAA;;;GAGG;AAEH;;;GAGG;AACH,MAAM,WAAW,KAAK;IACrB,sCAAsC;IACtC,GAAG,EAAE,MAAM,MAAM,CAAC;CAClB;AAED;;;GAGG;AACH,eAAO,MAAM,UAAU,EAAE,KAKxB,CAAC;AAEF;;;;;;;;;;;GAWG;AACH,eAAO,MAAM,aAAa,EAAE,KAI3B,CAAC;AAmCF;;;;GAIG;AACH,eAAO,MAAM,aAAa,EAAE,KAE3B,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,cAAc,OAAQ,CAAC;AACpC,eAAO,MAAM,cAAc,UAAY,CAAC;AACxC,eAAO,MAAM,eAAe,aAAgB,CAAC;AAE7C;;GAEG;AACH,eAAO,MAAM,aAAa,GAAI,IAAI,MAAM,KAAG,MAA6B,CAAC;AAEzE;;GAEG;AACH,eAAO,MAAM,aAAa,GAAI,IAAI,MAAM,KAAG,MAA6B,CAAC;AAEzE;;GAEG;AACH,eAAO,MAAM,cAAc,GAAI,IAAI,MAAM,KAAG,MAA8B,CAAC;AAE3E;;GAEG;AACH,MAAM,MAAM,QAAQ,GAAG,IAAI,GAAG,IAAI,GAAG,IAAI,GAAG,GAAG,CAAC;AAEhD;;;;;GAKG;AACH,eAAO,MAAM,qBAAqB,GAAI,WAAW,KAAK,CAAC,MAAM,CAAC,KAAG,QAqBhE,CAAC;AAEF;;;;;;GAMG;AACH,eAAO,MAAM,WAAW,GAAI,IAAI,MAAM,EAAE,MAAM,QAAQ,EAAE,WAAU,MAAU,KAAG,MAa9E,CAAC;AAEF;;;;;;;;;;;;;GAaG;AACH,eAAO,MAAM,oBAAoB,GAAI,IAAI,MAAM,EAAE,WAAU,MAAU,KAAG,MAavE,CAAC;AAEF;;;GAGG;AACH,MAAM,WAAW,UAAU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