-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathzap.h
More file actions
3036 lines (2597 loc) · 104 KB
/
Copy pathzap.h
File metadata and controls
3036 lines (2597 loc) · 104 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* zap.h - STB-style single-header benchmarking library for C
*
* Inspired by criterion-rs (Rust benchmarking framework)
*
* USAGE:
* In exactly ONE C file, before including this header:
* #define ZAP_IMPLEMENTATION
* #include "zap.h"
*
* In all other files, just:
* #include "zap.h"
*
* EXAMPLE:
* void bench_example(zap_t* c) {
* ZAP_LOOP(c) {
* // code to benchmark
* }
* }
*
* ZAP_GROUP(my_benches, bench_example);
* ZAP_MAIN(my_benches);
*
* LICENSE: MIT (see end of file)
*/
#ifndef ZAP_H
#define ZAP_H
#ifdef __cplusplus
extern "C" {
#endif
/* CONFIGURATION */
// Measurement defaults
#ifndef ZAP_DEFAULT_SAMPLE_COUNT
#define ZAP_DEFAULT_SAMPLE_COUNT 100
#endif
#ifndef ZAP_DEFAULT_WARMUP_TIME_NS
#define ZAP_DEFAULT_WARMUP_TIME_NS 1000000000ULL // 1 second
#endif
#ifndef ZAP_DEFAULT_MEASUREMENT_TIME_NS
#define ZAP_DEFAULT_MEASUREMENT_TIME_NS 3000000000ULL // 3 seconds
#endif
#ifndef ZAP_DEFAULT_MIN_ITERS
#define ZAP_DEFAULT_MIN_ITERS 0 // 0 = auto
#endif
#ifndef ZAP_CONFIDENCE_LEVEL
#define ZAP_CONFIDENCE_LEVEL 0.95
#endif
// Output defaults (0 = off, 1 = on)
#ifndef ZAP_DEFAULT_SHOW_ENV
#define ZAP_DEFAULT_SHOW_ENV 0
#endif
#ifndef ZAP_DEFAULT_SHOW_HISTOGRAM
#define ZAP_DEFAULT_SHOW_HISTOGRAM 0
#endif
#ifndef ZAP_DEFAULT_SHOW_PERCENTILES
#define ZAP_DEFAULT_SHOW_PERCENTILES 0
#endif
// Color mode: 0 = auto, 1 = always, 2 = never
#ifndef ZAP_DEFAULT_COLOR_MODE
#define ZAP_DEFAULT_COLOR_MODE 0
#endif
/* INCLUDES */
#include <stdint.h>
#include <stddef.h>
#include <stdbool.h>
/* TYPES */
// Throughput type
typedef enum zap_throughput_type {
ZAP_THROUGHPUT_NONE = 0,
ZAP_THROUGHPUT_BYTES,
ZAP_THROUGHPUT_ELEMENTS
} zap_throughput_type_t;
// Statistics results
typedef struct zap_stats {
double mean; // Average
double median; // Same as p50
double std_dev; // Standard deviation
double mad; // Median Absolute Deviation
double ci_lower; // Confidence interval lower bound
double ci_upper; // Confidence interval upper bound
double min; // Minimum sample value
double max; // Maximum sample value
double p75; // 75th percentile
double p90; // 90th percentile
double p95; // 95th percentile
double p99; // 99th percentile
size_t outliers_low; // Number of low outliers
size_t outliers_high; // Number of high outliers
size_t sample_count; // Number of samples
size_t iterations; // Iterations per sample
double* samples; // Pointer to samples for histogram
// Throughput info
zap_throughput_type_t throughput_type;
size_t throughput_value; /* Bytes or elements per iteration */
} zap_stats_t;
// Per-benchmark configuration
typedef struct zap_bench_config {
uint64_t warmup_time_ns;
uint64_t measurement_time_ns;
size_t sample_count;
} zap_bench_config_t;
// Benchmark state
typedef struct criterion {
const char* name;
uint64_t iterations;
uint64_t current_iter;
uint64_t start_time;
double* samples;
size_t sample_count;
size_t sample_capacity;
bool warmup_complete;
bool measuring;
bool status_printed; // Track if warmup/measuring status was shown
zap_bench_config_t config;
// Throughput tracking
zap_throughput_type_t throughput_type;
size_t throughput_value;
} zap_t;
// Forward declaration for bencher
typedef struct zap_bencher zap_bencher_t;
// Benchmark function signatures
typedef void (*zap_bench_fn)(zap_t*);
typedef void (*zap_bencher_fn)(zap_bencher_t*);
typedef void (*zap_param_fn)(zap_bencher_t*, void* param);
// Benchmark entry
typedef struct zap_bench {
const char* name;
zap_bench_fn func;
} zap_bench_t;
// Static benchmark group (from ZAP_GROUP macro)
typedef struct zap_group {
const char* name;
const zap_bench_t* benches;
size_t count;
} zap_group_t;
// Setup/teardown function types
typedef void (*zap_setup_fn)(void);
typedef void (*zap_teardown_fn)(void);
// Maximum tags per benchmark group
#ifndef ZAP_MAX_TAGS
#define ZAP_MAX_TAGS 8
#endif
// Runtime benchmark group
typedef struct zap_runtime_group {
char name[128];
zap_bench_config_t config;
bool active;
bool header_printed; // Deferred header for filtering
zap_setup_fn setup; // Called before group runs
zap_teardown_fn teardown; // Called after group completes
// Tags for filtering
char tags[ZAP_MAX_TAGS][32];
size_t tag_count;
} zap_runtime_group_t;
// Bencher - passed to iter() style benchmarks
struct zap_bencher {
zap_t* state;
zap_runtime_group_t* group;
char full_name[256];
};
// Benchmark ID for parameterized benchmarks
typedef struct zap_benchmark_id {
char label[128];
char param_str[64];
} zap_benchmark_id_t;
// Comparison result
typedef enum zap_change {
ZAP_NO_CHANGE,
ZAP_IMPROVED,
ZAP_REGRESSED
} zap_change_t;
// Baseline entry for a single benchmark
typedef struct zap_baseline_entry {
char name[256];
double mean;
double std_dev;
double ci_lower;
double ci_upper;
} zap_baseline_entry_t;
// Baseline storage
typedef struct zap_baseline {
zap_baseline_entry_t* entries;
size_t count;
size_t capacity;
} zap_baseline_t;
// Comparison result for a single benchmark
typedef struct zap_comparison {
const char* name;
double old_mean;
double new_mean;
double change_pct; // Percentage change (negative = faster)
zap_change_t change;
bool significant; // Statistically significant?
} zap_comparison_t;
// Color output mode
typedef enum zap_color_mode {
ZAP_COLOR_AUTO = 0, // Auto-detect TTY
ZAP_COLOR_ALWAYS, // Always use colors
ZAP_COLOR_NEVER // Never use colors
} zap_color_mode_t;
// Environment information
typedef struct zap_env {
char cpu_model[128];
char os_info[64];
char compiler[64];
int cpu_cores;
int cpu_threads;
// SIMD capabilities
bool has_sse;
bool has_sse2;
bool has_sse3;
bool has_ssse3;
bool has_sse41;
bool has_sse42;
bool has_avx;
bool has_avx2;
bool has_avx512f;
bool has_neon;
} zap_env_t;
// Maximum implementations in a comparison group
#ifndef ZAP_MAX_IMPLS
#define ZAP_MAX_IMPLS 8
#endif
// Result for a single implementation in a comparison
typedef struct zap_impl_result {
char name[64];
zap_stats_t stats;
bool valid;
} zap_impl_result_t;
// Comparison group configuration
typedef struct zap_compare_group {
char name[128];
zap_bench_config_t config;
size_t baseline_idx;
bool header_printed;
char tags[ZAP_MAX_TAGS][32];
size_t tag_count;
} zap_compare_group_t;
// Comparison context for a single benchmark with multiple implementations
typedef struct zap_compare_ctx {
zap_compare_group_t* group;
zap_benchmark_id_t id;
zap_impl_result_t results[ZAP_MAX_IMPLS];
size_t impl_count;
void* input;
size_t input_size;
bool skipped; // Set if filtered out or dry-run
} zap_compare_ctx_t;
// Maximum CLI tags for filtering
#ifndef ZAP_MAX_CLI_TAGS
#define ZAP_MAX_CLI_TAGS 16
#endif
// Global configuration
typedef struct zap_config {
const char* baseline_path;
const char* filter; // Benchmark name filter pattern
double fail_threshold; // Exit non-zero if regression > this %
bool save_baseline; // Save a file within .zap to compare with future benches
bool compare; // Whether to compare with a baseline or not
bool explicit_path; // User specified a custom path
bool json_output; // Output results as JSON
bool has_regression; /* Track if any benchmark regressed beyond threshold */
zap_color_mode_t color_mode; // Color output mode
bool dry_run; // List benchmarks without running
// CLI overrides for benchmark settings
size_t cli_samples; // 0 = use default
uint64_t cli_warmup_ns; // 0 = use default
uint64_t cli_time_ns; // 0 = use default
uint64_t cli_min_iters; // 0 = use default
// Tag filtering
char cli_tags[ZAP_MAX_CLI_TAGS][32];
size_t cli_tag_count;
// Output verbosity flags (text only, JSON always shows all)
bool show_env; // Show environment info
bool show_histogram; // Show distribution histogram
bool show_percentiles;/* Show p75/p90/p95/p99 */
zap_baseline_t baseline;
zap_env_t env; // System environment info
} zap_config_t;
// Global config instance
extern zap_config_t zap_g_config;
/* API DECLARATIONS */
// Timing functions
uint64_t zap_now_ns(void);
// Statistics functions
double zap_mean(const double* samples, size_t n);
double zap_median(double* samples, size_t n);
double zap_percentile(const double* sorted_samples, size_t n, double p);
double zap_std_dev(const double* samples, size_t n, double mean);
double zap_mad(double* samples, size_t n, double median);
void zap_confidence_interval(const double* samples, size_t n,
double mean, double std_dev,
double* ci_lower, double* ci_upper);
void zap_detect_outliers(const double* samples, size_t n,
double median, double mad,
size_t* low, size_t* high);
zap_stats_t zap_compute_stats(double* samples, size_t n);
// Black box - prevents compiler from optimizing away values
#define zap_black_box(val) zap__black_box_impl(&(val), sizeof(val))
void zap__black_box_impl(void* ptr, size_t size);
// Benchmark control
void zap_init(zap_t* c, const char* name);
void zap_cleanup(zap_t* c);
bool zap_loop_start(zap_t* c);
void zap_loop_end(zap_t* c);
// Reporting
void zap_report(const char* name, const zap_stats_t* stats);
void zap_report_json(const char* name, const zap_stats_t* stats,
const zap_comparison_t* cmp);
void zap_report_group_start(const char* name);
void zap_report_group_end(void);
// Runner
void zap_run_bench(const zap_bench_t* bench);
void zap_run_group(const zap_group_t* group);
// Runtime benchmark groups (criterion-rs style)
zap_runtime_group_t* zap_benchmark_group(const char* name);
void zap_group_measurement_time(zap_runtime_group_t* g, uint64_t ns);
void zap_group_warmup_time(zap_runtime_group_t* g, uint64_t ns);
void zap_group_sample_count(zap_runtime_group_t* g, size_t count);
void zap_group_setup(zap_runtime_group_t* g, zap_setup_fn setup);
void zap_group_teardown(zap_runtime_group_t* g, zap_teardown_fn teardown);
void zap_group_tag(zap_runtime_group_t* g, const char* tag);
void zap_group_finish(zap_runtime_group_t* g);
// Benchmark ID for parameterized benchmarks
zap_benchmark_id_t zap_benchmark_id(const char* label, int64_t param);
zap_benchmark_id_t zap_benchmark_id_str(const char* label, const char* param);
// Bencher functions (iter-style API)
void zap_bench_function(zap_runtime_group_t* g, const char* name,
zap_bencher_fn fn);
void zap_bench_with_input(zap_runtime_group_t* g,
zap_benchmark_id_t id,
void* input, size_t input_size,
zap_param_fn fn);
// iter() - run the benchmark closure
void zap_bencher_iter(zap_bencher_t* b, void (*fn)(void));
void zap_bencher_iter_custom(zap_bencher_t* b,
void (*setup)(void*),
void (*routine)(void*),
void (*teardown)(void*),
void* user_data);
// Throughput configuration
void zap_set_throughput_bytes(zap_t* c, size_t bytes_per_iter);
void zap_set_throughput_elements(zap_t* c, size_t elements_per_iter);
void zap_bencher_set_throughput_bytes(zap_bencher_t* b, size_t bytes_per_iter);
void zap_bencher_set_throughput_elements(zap_bencher_t* b, size_t elements_per_iter);
// Baseline management
void zap_baseline_init(zap_baseline_t* b);
void zap_baseline_free(zap_baseline_t* b);
void zap_baseline_add(zap_baseline_t* b, const char* name,
const zap_stats_t* stats);
const zap_baseline_entry_t* zap_baseline_find(
const zap_baseline_t* b, const char* name);
bool zap_baseline_save(const zap_baseline_t* b, const char* path);
bool zap_baseline_load(zap_baseline_t* b, const char* path);
// Comparison
zap_comparison_t zap_compare(const zap_baseline_entry_t* baseline,
const zap_stats_t* current);
void zap_report_comparison(const char* name, const zap_stats_t* stats,
const zap_comparison_t* cmp);
/* CLI argument parsing */
void zap_parse_args(int argc, char** argv);
// Filter matching
bool zap_matches_filter(const char* name, const char* pattern);
bool zap_group_matches_tags(const zap_runtime_group_t* g);
// Status messages
void zap_status_warmup(const char* name);
void zap_status_measuring(const char* name);
void zap_status_clear(void);
// Environment detection
void zap_env_detect(zap_env_t* env);
void zap_env_print(const zap_env_t* env);
void zap_env_print_json(const zap_env_t* env);
// Comparison API - compare multiple implementations
zap_compare_group_t* zap_compare_group(const char* name);
void zap_compare_set_baseline(zap_compare_group_t* g, size_t idx);
void zap_compare_tag(zap_compare_group_t* g, const char* tag);
zap_compare_ctx_t* zap_compare_begin(zap_compare_group_t* g,
zap_benchmark_id_t id,
void* input, size_t input_size);
void zap_compare_impl(zap_compare_ctx_t* ctx, const char* name, zap_param_fn fn);
void zap_compare_end(zap_compare_ctx_t* ctx);
void zap_compare_group_finish(zap_compare_group_t* g);
/* MACROS */
/*
* ZAP_LOOP - Main benchmarking loop
* Usage:
* ZAP_LOOP(c) {
* // code to benchmark
* }
*/
#define ZAP_LOOP(c) \
while (zap_loop_start(c)) \
for (uint64_t _crit_i = 0; \
_crit_i < (c)->iterations; \
++_crit_i)
/*
* After the loop body, we need to call zap_loop_end.
* This is handled by wrapping in a do-while with cleanup.
* Actually, let's use a different approach with a for-loop wrapper.
*/
#undef ZAP_LOOP
#define ZAP_LOOP(c) \
for (int _crit_done = 0; !_crit_done; ) \
for (; zap_loop_start(c); _crit_done = 1, zap_loop_end(c)) \
for (uint64_t _crit_i = 0; _crit_i < (c)->iterations; ++_crit_i)
/*
* ZAP_ITER - Single expression benchmark (like b.iter(|| expr))
* Usage:
* void bench_example(zap_bencher_t* b) {
* int data = 42;
* ZAP_ITER(b, {
* result = expensive_operation(data);
* zap_black_box(result);
* });
* }
*/
#define ZAP_ITER(b, block) \
do { \
zap_t* _c = (b)->state; \
ZAP_LOOP(_c) { \
block \
} \
} while (0)
/*
* Duration helper macros (convert to nanoseconds)
*/
#define ZAP_SECONDS(s) ((uint64_t)(s) * 1000000000ULL)
#define ZAP_MILLIS(ms) ((uint64_t)(ms) * 1000000ULL)
#define ZAP_MICROS(us) ((uint64_t)(us) * 1000ULL)
/*
* ZAP_GROUP - Define a benchmark group
* Usage:
* ZAP_GROUP(group_name, bench1, bench2, bench3);
*/
#define ZAP_GROUP(grpname, ...) \
static const zap_bench_t grpname##_benches[] = { \
ZAP__EXPAND_BENCHES(__VA_ARGS__) \
}; \
static const zap_group_t grpname = { \
#grpname, \
grpname##_benches, \
sizeof(grpname##_benches) / sizeof(grpname##_benches[0]) \
}
// Helper macro to expand benchmark function list
#define ZAP__EXPAND_BENCHES(...) \
ZAP__MAP(ZAP__BENCH_ENTRY, __VA_ARGS__)
#define ZAP__BENCH_ENTRY(fn) { #fn, fn },
// Macro mapping utilities
#define ZAP__MAP(macro, ...) \
ZAP__MAP_(__VA_ARGS__, \
ZAP__MAP_16, ZAP__MAP_15, ZAP__MAP_14, \
ZAP__MAP_13, ZAP__MAP_12, ZAP__MAP_11, \
ZAP__MAP_10, ZAP__MAP_9, ZAP__MAP_8, \
ZAP__MAP_7, ZAP__MAP_6, ZAP__MAP_5, \
ZAP__MAP_4, ZAP__MAP_3, ZAP__MAP_2, \
ZAP__MAP_1)(macro, __VA_ARGS__)
#define ZAP__MAP_(...) ZAP__MAP_N(__VA_ARGS__)
#define ZAP__MAP_N(_1,_2,_3,_4,_5,_6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,N,...) N
#define ZAP__MAP_1(m,a) m(a)
#define ZAP__MAP_2(m,a,...) m(a) ZAP__MAP_1(m,__VA_ARGS__)
#define ZAP__MAP_3(m,a,...) m(a) ZAP__MAP_2(m,__VA_ARGS__)
#define ZAP__MAP_4(m,a,...) m(a) ZAP__MAP_3(m,__VA_ARGS__)
#define ZAP__MAP_5(m,a,...) m(a) ZAP__MAP_4(m,__VA_ARGS__)
#define ZAP__MAP_6(m,a,...) m(a) ZAP__MAP_5(m,__VA_ARGS__)
#define ZAP__MAP_7(m,a,...) m(a) ZAP__MAP_6(m,__VA_ARGS__)
#define ZAP__MAP_8(m,a,...) m(a) ZAP__MAP_7(m,__VA_ARGS__)
#define ZAP__MAP_9(m,a,...) m(a) ZAP__MAP_8(m,__VA_ARGS__)
#define ZAP__MAP_10(m,a,...) m(a) ZAP__MAP_9(m,__VA_ARGS__)
#define ZAP__MAP_11(m,a,...) m(a) ZAP__MAP_10(m,__VA_ARGS__)
#define ZAP__MAP_12(m,a,...) m(a) ZAP__MAP_11(m,__VA_ARGS__)
#define ZAP__MAP_13(m,a,...) m(a) ZAP__MAP_12(m,__VA_ARGS__)
#define ZAP__MAP_14(m,a,...) m(a) ZAP__MAP_13(m,__VA_ARGS__)
#define ZAP__MAP_15(m,a,...) m(a) ZAP__MAP_14(m,__VA_ARGS__)
#define ZAP__MAP_16(m,a,...) m(a) ZAP__MAP_15(m,__VA_ARGS__)
/*
* ZAP_MAIN - Define main function that runs benchmark groups
* Usage:
* ZAP_MAIN(group1, group2);
*
* Supports CLI arguments:
* --save-baseline [FILE] Save results to baseline file
* --baseline [FILE] Compare against baseline file
* --compare [FILE] Alias for --baseline
* --json Output results as JSON
* --fail-threshold PCT Exit with code 1 if regression > PCT%
*/
#define ZAP_MAIN(...) \
int main(int argc, char** argv) { \
zap_parse_args(argc, argv); \
ZAP__MAP(ZAP__RUN_GROUP, __VA_ARGS__) \
return zap_finalize(); \
}
#define ZAP__RUN_GROUP(group) zap_run_group_internal(&group);
#ifdef __cplusplus
}
#endif
/* IMPLEMENTATION */
#ifdef ZAP_IMPLEMENTATION
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <time.h>
#include <sys/stat.h>
#include <unistd.h> // For isatty()
/* POSIX timing */
#if defined(__APPLE__)
#include <mach/mach_time.h>
#include <sys/sysctl.h>
#else
#include <time.h>
#endif
/* CPUID for x86/x64 SIMD detection */
#if defined(__x86_64__) || defined(_M_X64) || defined(__i386__) || defined(_M_IX86)
#define ZAP_X86 1
#if defined(__GNUC__) || defined(__clang__)
#include <cpuid.h>
#define ZAP_CPUID(leaf, a, b, c, d) __cpuid(leaf, a, b, c, d)
#define ZAP_CPUID_COUNT(leaf, sub, a, b, c, d) __cpuid_count(leaf, sub, a, b, c, d)
#elif defined(_MSC_VER)
#include <intrin.h>
#define ZAP_CPUID(leaf, a, b, c, d) do { \
int regs[4]; __cpuid(regs, leaf); \
a = regs[0]; b = regs[1]; c = regs[2]; d = regs[3]; \
} while(0)
#define ZAP_CPUID_COUNT(leaf, sub, a, b, c, d) do { \
int regs[4]; __cpuidex(regs, leaf, sub); \
a = regs[0]; b = regs[1]; c = regs[2]; d = regs[3]; \
} while(0)
#endif
#endif
/* ARM NEON detection */
#if defined(__aarch64__) || defined(_M_ARM64)
#define ZAP_ARM64 1
#endif
/* UTILITY MACROS */
#if defined(__GNUC__) || defined(__clang__)
#define ZAP_UNUSED __attribute__((unused))
#else
#define ZAP_UNUSED
#endif
/* ANSI COLOR CODES - Synthwave palette */
#define ZAP_COLOR_RESET "\033[0m"
#define ZAP_COLOR_BOLD "\033[1m"
#define ZAP_COLOR_DIM "\033[2m"
// Synthwave neon/fluorescent colors (true color RGB)
#define ZAP_COLOR_GREEN "\033[38;2;57;255;20m" // Fluorescent green
#define ZAP_COLOR_YELLOW "\033[38;2;255;170;0m" // Neon orange/yellow
#define ZAP_COLOR_BLUE "\033[38;2;0;191;255m" // Electric blue
#define ZAP_COLOR_MAGENTA "\033[38;2;255;16;240m" // Neon pink
#define ZAP_COLOR_CYAN "\033[38;2;0;255;255m" // Electric cyan
#define ZAP_COLOR_RED "\033[38;2;255;0;63m" // Neon red
#define ZAP_COLOR_PURPLE "\033[38;2;191;0;255m" // Neon purple
/* ENVIRONMENT DETECTION */
static void zap__detect_cpu_model(zap_env_t* env) {
#if defined(__APPLE__)
size_t size = sizeof(env->cpu_model);
if (sysctlbyname("machdep.cpu.brand_string", env->cpu_model, &size, NULL, 0) != 0) {
strncpy(env->cpu_model, "Unknown", sizeof(env->cpu_model));
}
#elif defined(__linux__)
FILE* f = fopen("/proc/cpuinfo", "r");
if (f) {
char line[256];
while (fgets(line, sizeof(line), f)) {
if (strncmp(line, "model name", 10) == 0) {
char* colon = strchr(line, ':');
if (colon) {
colon++;
while (*colon == ' ' || *colon == '\t') colon++;
char* nl = strchr(colon, '\n');
if (nl) *nl = '\0';
strncpy(env->cpu_model, colon, sizeof(env->cpu_model) - 1);
}
break;
}
}
fclose(f);
} else {
strncpy(env->cpu_model, "Unknown", sizeof(env->cpu_model));
}
#else
strncpy(env->cpu_model, "Unknown", sizeof(env->cpu_model));
#endif
env->cpu_model[sizeof(env->cpu_model) - 1] = '\0';
}
static void zap__detect_cpu_cores(zap_env_t* env) {
#if defined(__APPLE__)
size_t size = sizeof(env->cpu_cores);
sysctlbyname("hw.physicalcpu", &env->cpu_cores, &size, NULL, 0);
size = sizeof(env->cpu_threads);
sysctlbyname("hw.logicalcpu", &env->cpu_threads, &size, NULL, 0);
#elif defined(_SC_NPROCESSORS_ONLN)
env->cpu_threads = (int)sysconf(_SC_NPROCESSORS_ONLN);
env->cpu_cores = env->cpu_threads; // Approximate
#else
env->cpu_cores = 1;
env->cpu_threads = 1;
#endif
}
static void zap__detect_os(zap_env_t* env) {
#if defined(__APPLE__)
char version[32] = "";
size_t size = sizeof(version);
sysctlbyname("kern.osproductversion", version, &size, NULL, 0);
snprintf(env->os_info, sizeof(env->os_info), "macOS %s", version);
#elif defined(__linux__)
FILE* f = fopen("/etc/os-release", "r");
if (f) {
char line[128];
while (fgets(line, sizeof(line), f)) {
if (strncmp(line, "PRETTY_NAME=", 12) == 0) {
char* start = strchr(line, '"');
if (start) {
start++;
char* end = strchr(start, '"');
if (end) *end = '\0';
strncpy(env->os_info, start, sizeof(env->os_info) - 1);
}
break;
}
}
fclose(f);
} else {
strncpy(env->os_info, "Linux", sizeof(env->os_info));
}
#elif defined(_WIN32)
strncpy(env->os_info, "Windows", sizeof(env->os_info));
#else
strncpy(env->os_info, "Unknown OS", sizeof(env->os_info));
#endif
env->os_info[sizeof(env->os_info) - 1] = '\0';
}
static void zap__detect_compiler(zap_env_t* env) {
#if defined(__clang__)
snprintf(env->compiler, sizeof(env->compiler), "Clang %d.%d.%d",
__clang_major__, __clang_minor__, __clang_patchlevel__);
#elif defined(__GNUC__)
snprintf(env->compiler, sizeof(env->compiler), "GCC %d.%d.%d",
__GNUC__, __GNUC_MINOR__, __GNUC_PATCHLEVEL__);
#elif defined(_MSC_VER)
snprintf(env->compiler, sizeof(env->compiler), "MSVC %d", _MSC_VER);
#else
strncpy(env->compiler, "Unknown compiler", sizeof(env->compiler));
#endif
env->compiler[sizeof(env->compiler) - 1] = '\0';
}
static void zap__detect_simd(zap_env_t* env) {
env->has_sse = false;
env->has_sse2 = false;
env->has_sse3 = false;
env->has_ssse3 = false;
env->has_sse41 = false;
env->has_sse42 = false;
env->has_avx = false;
env->has_avx2 = false;
env->has_avx512f = false;
env->has_neon = false;
#if defined(ZAP_X86)
unsigned int eax, ebx, ecx, edx;
// Check CPUID availability and get feature flags
ZAP_CPUID(1, eax, ebx, ecx, edx);
env->has_sse = (edx & (1 << 25)) != 0;
env->has_sse2 = (edx & (1 << 26)) != 0;
env->has_sse3 = (ecx & (1 << 0)) != 0;
env->has_ssse3 = (ecx & (1 << 9)) != 0;
env->has_sse41 = (ecx & (1 << 19)) != 0;
env->has_sse42 = (ecx & (1 << 20)) != 0;
env->has_avx = (ecx & (1 << 28)) != 0;
// Check for AVX2 and AVX-512 (need extended features)
ZAP_CPUID(0, eax, ebx, ecx, edx);
if (eax >= 7) {
ZAP_CPUID_COUNT(7, 0, eax, ebx, ecx, edx);
env->has_avx2 = (ebx & (1 << 5)) != 0;
env->has_avx512f = (ebx & (1 << 16)) != 0;
}
#endif
#if defined(ZAP_ARM64)
// ARM64 always has NEON
env->has_neon = true;
#elif defined(__ARM_NEON) || defined(__ARM_NEON__)
env->has_neon = true;
#endif
}
void zap_env_detect(zap_env_t* env) {
memset(env, 0, sizeof(*env));
zap__detect_cpu_model(env);
zap__detect_cpu_cores(env);
zap__detect_os(env);
zap__detect_compiler(env);
zap__detect_simd(env);
}
/* TIMING IMPLEMENTATION */
uint64_t zap_now_ns(void) {
#if defined(__APPLE__)
static mach_timebase_info_data_t timebase = {0};
if (timebase.denom == 0) {
mach_timebase_info(&timebase);
}
return mach_absolute_time() * timebase.numer / timebase.denom;
#else
struct timespec ts;
clock_gettime(CLOCK_MONOTONIC, &ts);
return (uint64_t)ts.tv_sec * 1000000000ULL + (uint64_t)ts.tv_nsec;
#endif
}
/* STATISTICS IMPLEMENTATION */
static int zap__cmp_double(const void* a, const void* b) {
double da = *(const double*)a;
double db = *(const double*)b;
return (da > db) - (da < db);
}
double zap_mean(const double* samples, size_t n) {
if (n == 0) return 0.0;
double sum = 0.0;
for (size_t i = 0; i < n; i++) {
sum += samples[i];
}
return sum / (double)n;
}
double zap_median(double* samples, size_t n) {
if (n == 0) return 0.0;
qsort(samples, n, sizeof(double), zap__cmp_double);
if (n % 2 == 0) {
return (samples[n/2 - 1] + samples[n/2]) / 2.0;
}
return samples[n/2];
}
double zap_percentile(const double* sorted_samples, size_t n, double p) {
if (n == 0) return 0.0;
if (n == 1) return sorted_samples[0];
double rank = (p / 100.0) * (n - 1);
size_t lower = (size_t)rank;
size_t upper = lower + 1;
if (upper >= n) upper = n - 1;
double frac = rank - (double)lower;
return sorted_samples[lower] * (1.0 - frac) + sorted_samples[upper] * frac;
}
double zap_std_dev(const double* samples, size_t n, double mean) {
if (n < 2) return 0.0;
double sum_sq = 0.0;
for (size_t i = 0; i < n; i++) {
double diff = samples[i] - mean;
sum_sq += diff * diff;
}
return sqrt(sum_sq / (double)(n - 1));
}
double zap_mad(double* samples, size_t n, double median) {
if (n == 0) return 0.0;
double* deviations = (double*)malloc(n * sizeof(double));
if (!deviations) return 0.0;
for (size_t i = 0; i < n; i++) {
deviations[i] = fabs(samples[i] - median);
}
double result = zap_median(deviations, n);
free(deviations);
return result;
}
void zap_confidence_interval(const double* samples, size_t n,
double mean, double std_dev,
double* ci_lower, double* ci_upper) {
(void)samples; // CI computed from mean/std_dev directly
// Using t-distribution approximation for 95% CI
// For large n, t approaches 1.96
double t = 1.96;
if (n < 30) {
// Rough approximation for small samples
static const double t_values[] = {
12.71, 4.30, 3.18, 2.78, 2.57, // n = 2-6
2.45, 2.36, 2.31, 2.26, 2.23, // n = 7-11
2.20, 2.18, 2.16, 2.14, 2.13, // n = 12-16
2.12, 2.11, 2.10, 2.09, 2.09, // n = 17-21
2.08, 2.07, 2.07, 2.06, 2.06, // n = 22-26
2.05, 2.05, 2.05 // n = 27-29
};
if (n >= 2) {
t = t_values[n - 2];
}
}
double margin = t * std_dev / sqrt((double)n);
*ci_lower = mean - margin;
*ci_upper = mean + margin;
}
void zap_detect_outliers(const double* samples, size_t n,
double median, double mad,
size_t* low, size_t* high) {
*low = 0;
*high = 0;
if (n == 0 || mad == 0.0) return;
// Modified Z-score threshold (common value is 3.5)
const double threshold = 3.5;
// 0.6745 = 1/1.4826, where 1.4826 is consistency constant for normal dist
for (size_t i = 0; i < n; i++) {
double modified_z = 0.6745 * (samples[i] - median) / mad;
if (modified_z < -threshold) {
(*low)++;
} else if (modified_z > threshold) {
(*high)++;
}
}
}
zap_stats_t zap_compute_stats(double* samples, size_t n) {
zap_stats_t stats = {0};
if (n == 0) return stats;
stats.sample_count = n;
stats.samples = samples; // Keep reference for histogram
// Calculate min/max
stats.min = samples[0];
stats.max = samples[0];
for (size_t i = 1; i < n; i++) {
if (samples[i] < stats.min) stats.min = samples[i];
if (samples[i] > stats.max) stats.max = samples[i];
}
// Need a copy for median since it sorts
double* sorted = (double*)malloc(n * sizeof(double));
if (!sorted) return stats;
memcpy(sorted, samples, n * sizeof(double));
stats.mean = zap_mean(samples, n);
stats.median = zap_median(sorted, n); // sorted is now sorted
stats.std_dev = zap_std_dev(samples, n, stats.mean);
// Calculate percentiles from sorted data
stats.p75 = zap_percentile(sorted, n, 75.0);
stats.p90 = zap_percentile(sorted, n, 90.0);
stats.p95 = zap_percentile(sorted, n, 95.0);
stats.p99 = zap_percentile(sorted, n, 99.0);
// Need fresh copy for MAD calculation (it sorts internally)
memcpy(sorted, samples, n * sizeof(double));
stats.mad = zap_mad(sorted, n, stats.median);
zap_confidence_interval(samples, n, stats.mean, stats.std_dev,
&stats.ci_lower, &stats.ci_upper);
zap_detect_outliers(samples, n, stats.median, stats.mad,
&stats.outliers_low, &stats.outliers_high);
free(sorted);
return stats;
}
/* BLACK BOX IMPLEMENTATION */
// Prevent compiler from optimizing away the value
void zap__black_box_impl(void* ptr, size_t size) {
(void)size;
__asm__ volatile("" : : "g"(ptr) : "memory");
}
/* STATUS MESSAGE IMPLEMENTATION */
static int zap__is_tty = -1; // -1 = not checked yet
static int zap__check_tty(void) {
if (zap__is_tty < 0) {
zap__is_tty = isatty(STDOUT_FILENO);
}
return zap__is_tty;
}
// Check if colors should be used based on color_mode setting
static int zap__use_colors(void) {
switch (zap_g_config.color_mode) {
case ZAP_COLOR_ALWAYS: return 1;
case ZAP_COLOR_NEVER: return 0;
default: return zap__check_tty();
}
}
// Conditional color codes - return empty string if colors disabled
static ZAP_UNUSED const char* zap__c_reset(void) { return zap__use_colors() ? ZAP_COLOR_RESET : ""; }
static ZAP_UNUSED const char* zap__c_bold(void) { return zap__use_colors() ? ZAP_COLOR_BOLD : ""; }
static ZAP_UNUSED const char* zap__c_dim(void) { return zap__use_colors() ? ZAP_COLOR_DIM : ""; }
static ZAP_UNUSED const char* zap__c_green(void) { return zap__use_colors() ? ZAP_COLOR_GREEN : ""; }
static ZAP_UNUSED const char* zap__c_yellow(void) { return zap__use_colors() ? ZAP_COLOR_YELLOW : ""; }
static ZAP_UNUSED const char* zap__c_blue(void) { return zap__use_colors() ? ZAP_COLOR_BLUE : ""; }
static ZAP_UNUSED const char* zap__c_cyan(void) { return zap__use_colors() ? ZAP_COLOR_CYAN : ""; }
static ZAP_UNUSED const char* zap__c_red(void) { return zap__use_colors() ? ZAP_COLOR_RED : ""; }
static ZAP_UNUSED const char* zap__c_magenta(void) { return zap__use_colors() ? ZAP_COLOR_MAGENTA : ""; }