| 1 | /* |
| 2 | * sc-membench - Portable Memory Bandwidth and Latency Benchmark |
| 3 | * |
| 4 | * A multi-platform memory benchmark that: |
| 5 | * - Works on Linux, macOS, FreeBSD, and other Unix-like systems |
| 6 | * - Works on x86, arm64, and other architectures |
| 7 | * - Measures read, write, and copy bandwidth using OpenMP |
| 8 | * - Measures memory latency using pointer chasing |
| 9 | * - Handles NUMA automatically (works on non-NUMA too) |
| 10 | * - Sweeps through cache and memory sizes |
| 11 | * - Finds optimal thread count for peak bandwidth |
| 12 | * - Outputs CSV format for analysis |
| 13 | * |
| 14 | * Compile (recommended - use make for auto-detection): |
| 15 | * make # Auto-detect available features |
| 16 | * make basic # Minimal build, no optional dependencies |
| 17 | * make full # All features (Linux: hwloc + numa + hugetlbfs) |
| 18 | * |
| 19 | * Manual compilation: |
| 20 | * gcc -O3 -fopenmp -o membench membench.c -lm |
| 21 | * # With optional libraries: |
| 22 | * gcc -O3 -fopenmp -DUSE_HWLOC -DUSE_NUMA -DHAVE_HUGETLBFS \ |
| 23 | * -o membench membench.c -lm -lhwloc -lnuma -lhugetlbfs |
| 24 | * |
| 25 | * Usage: |
| 26 | * ./membench [options] |
| 27 | * ./membench -h # Show help |
| 28 | * |
| 29 | * Copyright 2026 Spare Cores |
| 30 | * Licensed under Mozilla Public License 2.0 |
| 31 | */ |
| 32 | |
| 33 | /* Platform detection (may be overridden by compiler flags) */ |
| 34 | #if !defined(PLATFORM_LINUX) && !defined(PLATFORM_MACOS) && !defined(PLATFORM_BSD) |
| 35 | #if defined(__linux__) |
| 36 | #define PLATFORM_LINUX |
| 37 | #elif defined(__APPLE__) && defined(__MACH__) |
| 38 | #define PLATFORM_MACOS |
| 39 | #elif defined(__FreeBSD__) || defined(__OpenBSD__) || defined(__NetBSD__) || defined(__DragonFly__) |
| 40 | #define PLATFORM_BSD |
| 41 | #endif |
| 42 | #endif |
| 43 | |
| 44 | /* Enable GNU extensions on Linux for CPU affinity (must be before includes) */ |
| 45 | #ifdef PLATFORM_LINUX |
| 46 | #ifndef _GNU_SOURCE |
| 47 | #define _GNU_SOURCE |
| 48 | #endif |
| 49 | #endif |
| 50 | |
| 51 | #include <stdio.h> |
| 52 | #include <stdlib.h> |
| 53 | #include <string.h> |
| 54 | #include <stdint.h> |
| 55 | #include <stdbool.h> |
| 56 | #include <omp.h> |
| 57 | #include <time.h> |
| 58 | #include <unistd.h> |
| 59 | #include <errno.h> |
| 60 | #include <sys/mman.h> |
| 61 | #include <math.h> |
| 62 | |
| 63 | /* Platform-specific includes */ |
| 64 | #ifdef PLATFORM_LINUX |
| 65 | #include <sched.h> |
| 66 | #endif |
| 67 | |
| 68 | #ifdef PLATFORM_BSD |
| 69 | #include <sys/param.h> |
| 70 | #include <sys/cpuset.h> |
| 71 | #include <sys/sysctl.h> |
| 72 | #endif |
| 73 | |
| 74 | #ifdef PLATFORM_MACOS |
| 75 | #include <sys/sysctl.h> |
| 76 | #include <mach/mach.h> |
| 77 | #include <mach/thread_policy.h> |
| 78 | #endif |
| 79 | |
| 80 | /* Optional library: libhugetlbfs (Linux only, for huge page size detection) */ |
| 81 | #if defined(HAVE_HUGETLBFS) && defined(PLATFORM_LINUX) |
| 82 | #include <hugetlbfs.h> |
| 83 | #endif |
| 84 | |
| 85 | /* Optional library: NUMA support (Linux only) */ |
| 86 | #ifdef USE_NUMA |
| 87 | #include <numa.h> |
| 88 | #include <numaif.h> |
| 89 | #endif |
| 90 | |
| 91 | /* ============================================================================ |
| 92 | * Configuration |
| 93 | * ============================================================================ */ |
| 94 | |
| 95 | #define VERSION "1.2.2" |
| 96 | |
| 97 | /* Target time per individual measurement (seconds) */ |
| 98 | #define TARGET_TIME_PER_TEST 0.25 |
| 99 | |
| 100 | /* Minimum iterations per test (keep low for large buffers that take seconds per iteration) */ |
| 101 | #define MIN_ITERATIONS 3 |
| 102 | |
| 103 | /* Maximum iterations per test */ |
| 104 | #define MAX_ITERATIONS 10000000 |
| 105 | |
| 106 | /* Default total runtime target (seconds). 0 = unlimited */ |
| 107 | #define DEFAULT_MAX_RUNTIME 0 |
| 108 | |
| 109 | /* Fixed RAM sizes for when we need to measure pure memory bandwidth */ |
| 110 | #define RAM_SIZE_1 (64UL * 1024 * 1024) /* 64 MB - definitely past any L3 */ |
| 111 | #define RAM_SIZE_2 (256UL * 1024 * 1024) /* 256 MB - more RAM data points */ |
| 112 | |
| 113 | /* Get huge page size dynamically from the system. |
| 114 | * Tries multiple methods in order of reliability: |
| 115 | * 1. libhugetlbfs (if available, most reliable) |
| 116 | * 2. /proc/meminfo (Linux) |
| 117 | * 3. sysctl (macOS/BSD) |
| 118 | * 4. Default fallback (2MB for x86, common size) |
| 119 | * Returns the default huge page size (typically 2MB on x86, varies on ARM). */ |
| 120 | static size_t get_huge_page_size(void) { |
| 121 | static size_t cached_size = 0; |
| 122 | if (cached_size != 0) return cached_size; |
| 123 | |
| 124 | #if defined(HAVE_HUGETLBFS) && defined(PLATFORM_LINUX) |
| 125 | /* Method 1: libhugetlbfs (most reliable on Linux) */ |
| 126 | long size = gethugepagesize(); |
| 127 | if (size > 0) { |
| 128 | cached_size = (size_t)size; |
| 129 | return cached_size; |
| 130 | } |
| 131 | #endif |
| 132 | |
| 133 | #ifdef PLATFORM_LINUX |
| 134 | /* Method 2: Parse /proc/meminfo */ |
| 135 | FILE *file = fopen("/proc/meminfo", "r"); |
| 136 | if (file) { |
| 137 | char line[256]; |
| 138 | unsigned long size_kb = 0; |
| 139 | while (fgets(line, sizeof(line), file)) { |
| 140 | if (sscanf(line, "Hugepagesize: %lu kB", &size_kb) == 1) { |
| 141 | cached_size = size_kb * 1024; |
| 142 | fclose(file); |
| 143 | return cached_size; |
| 144 | } |
| 145 | } |
| 146 | fclose(file); |
| 147 | } |
| 148 | #endif |
| 149 | |
| 150 | #if defined(PLATFORM_MACOS) || defined(PLATFORM_BSD) |
| 151 | /* Method 3: sysctl for macOS/BSD (get VM page size, huge pages vary) */ |
| 152 | /* Note: macOS doesn't have traditional huge pages like Linux, |
| 153 | * but we can use vm.pagesize as a reference. Superpage support varies. */ |
| 154 | int mib[2] = { CTL_HW, HW_PAGESIZE }; |
| 155 | int pagesize = 0; |
| 156 | size_t len = sizeof(pagesize); |
| 157 | if (sysctl(mib, 2, &pagesize, &len, NULL, 0) == 0 && pagesize > 0) { |
| 158 | /* On macOS, superpage size is typically 2MB on Intel, 16KB on ARM |
| 159 | * but there's no standard API to query it. Use 2MB as common default. */ |
| 160 | cached_size = 2UL * 1024 * 1024; |
| 161 | return cached_size; |
| 162 | } |
| 163 | #endif |
| 164 | |
| 165 | /* Method 4: Default fallback (2MB, most common huge page size) */ |
| 166 | cached_size = 2UL * 1024 * 1024; |
| 167 | return cached_size; |
| 168 | } |
| 169 | |
| 170 | /* Minimum buffer size to use huge pages (2 huge pages). |
| 171 | * Below this threshold, TLB pressure isn't significant and huge pages |
| 172 | * would waste memory (each allocation rounds up to huge page boundary). */ |
| 173 | static size_t get_huge_page_threshold(void) { |
| 174 | return 2 * get_huge_page_size(); |
| 175 | } |
| 176 | |
| 177 | /* ============================================================================ |
| 178 | * Types |
| 179 | * ============================================================================ */ |
| 180 | |
| 181 | typedef enum { |
| 182 | OP_READ, |
| 183 | OP_WRITE, |
| 184 | OP_COPY, |
| 185 | OP_LATENCY /* Memory latency test using pointer chasing */ |
| 186 | } operation_t; |
| 187 | |
| 188 | static const char* OP_NAMES[] = {"read", "write", "copy", "latency"}; |
| 189 | |
| 190 | typedef struct { |
| 191 | size_t size; |
| 192 | operation_t op; |
| 193 | int threads; |
| 194 | double bandwidth_mb_s; /* For read/write/copy */ |
| 195 | double latency_ns; /* For latency test (median) */ |
| 196 | double latency_mean_ns; /* For latency test (mean) */ |
| 197 | double latency_stddev_ns; /* For latency test (standard deviation) */ |
| 198 | double latency_cv; /* Coefficient of variation (stddev/mean) */ |
| 199 | int latency_samples; /* Number of samples for latency measurement */ |
| 200 | double elapsed_s; |
| 201 | int iterations; |
| 202 | } result_t; |
| 203 | |
| 204 | /* Summary statistics structure */ |
| 205 | typedef struct { |
| 206 | /* Peak bandwidth for large buffer sizes (RAM speed) */ |
| 207 | double peak_read_mb_s; |
| 208 | double peak_write_mb_s; |
| 209 | double peak_copy_mb_s; |
| 210 | |
| 211 | /* Best latency for large buffer sizes (RAM latency) */ |
| 212 | double best_latency_ns; |
| 213 | |
| 214 | /* Weighted average bandwidth (larger sizes weighted more) */ |
| 215 | double weighted_avg_read_mb_s; |
| 216 | double weighted_avg_write_mb_s; |
| 217 | double weighted_avg_copy_mb_s; |
| 218 | |
| 219 | /* Counts and weights for weighted average */ |
| 220 | double read_weight_sum; |
| 221 | double write_weight_sum; |
| 222 | double copy_weight_sum; |
| 223 | double read_bw_weighted_sum; |
| 224 | double write_bw_weighted_sum; |
| 225 | double copy_bw_weighted_sum; |
| 226 | |
| 227 | /* Track the largest size tested for "RAM" results */ |
| 228 | size_t largest_size_tested; |
| 229 | |
| 230 | /* Count of measurements */ |
| 231 | int read_count; |
| 232 | int write_count; |
| 233 | int copy_count; |
| 234 | int latency_count; |
| 235 | } summary_t; |
| 236 | |
| 237 | static summary_t g_summary = {0}; |
| 238 | |
| 239 | /* ============================================================================ |
| 240 | * Global state |
| 241 | * ============================================================================ */ |
| 242 | |
| 243 | static volatile int g_running = 1; |
| 244 | static int g_verbose = 0; /* 0=quiet, 1=summary, 2=detailed */ |
| 245 | static int g_full_sweep = 0; /* If 1, test all sizes up to max; if 0, stop early when converged */ |
| 246 | static size_t g_single_size = 0; /* If > 0, test only this size (in bytes) */ |
| 247 | static int g_human_readable = 0; /* If 1, output human-readable format instead of CSV */ |
| 248 | static int g_num_cpus = 0; |
| 249 | static int g_numa_nodes = 0; |
| 250 | static size_t g_total_memory = 0; |
| 251 | |
| 252 | /* NUMA topology - CPUs per node for balanced thread distribution */ |
| 253 | #define MAX_NUMA_NODES 64 |
| 254 | #define MAX_CPUS_PER_NODE 512 |
| 255 | static int g_cpus_per_node[MAX_NUMA_NODES]; /* Count of CPUs on each node */ |
| 256 | static int g_node_cpus[MAX_NUMA_NODES][MAX_CPUS_PER_NODE]; /* CPU IDs for each node */ |
| 257 | /* Number of times to run each benchmark, taking best result (like lmbench TRIES=11) */ |
| 258 | #define DEFAULT_BENCHMARK_TRIES 3 |
| 259 | static int g_benchmark_tries = DEFAULT_BENCHMARK_TRIES; |
| 260 | |
| 261 | /* Thread count options: |
| 262 | * g_explicit_threads > 0: use exactly that many threads |
| 263 | * g_explicit_threads == 0: use num_cpus (default) |
| 264 | * g_auto_scaling: try multiple thread counts to find best */ |
| 265 | static int g_explicit_threads = 0; |
| 266 | static int g_auto_scaling = 0; |
| 267 | |
| 268 | static double g_max_runtime = DEFAULT_MAX_RUNTIME; |
| 269 | |
| 270 | /* Huge pages support */ |
| 271 | static int g_use_hugepages = 0; |
| 272 | |
| 273 | /* Operation selection bitmask (bit 0=read, 1=write, 2=copy, 3=latency) */ |
| 274 | #define OP_MASK_ALL 0x0F /* All operations enabled */ |
| 275 | static int g_ops_mask = OP_MASK_ALL; |
| 276 | |
| 277 | |
| 278 | /* Detected cache sizes (per core) */ |
| 279 | static size_t g_l1_cache_size = 0; |
| 280 | static size_t g_l2_cache_size = 0; |
| 281 | static size_t g_l3_cache_size = 0; |
| 282 | |
| 283 | /* Minimum total buffer size - adaptive based on cache topology */ |
| 284 | static size_t g_min_total_size = 4096; /* Default 4KB, updated after cache detection */ |
| 285 | |
| 286 | /* ============================================================================ |
| 287 | * Timing |
| 288 | * ============================================================================ */ |
| 289 | |
| 290 | static inline double get_time(void) { |
| 291 | struct timespec ts; |
| 292 | clock_gettime(CLOCK_MONOTONIC, &ts); |
| 293 | return ts.tv_sec + ts.tv_nsec * 1e-9; |
| 294 | } |
| 295 | |
| 296 | /* ============================================================================ |
| 297 | * Memory operations |
| 298 | * ============================================================================ */ |
| 299 | |
| 300 | /* Prevent compiler from optimizing away operations */ |
| 301 | static volatile uint64_t g_sink = 0; |
| 302 | |
| 303 | /* |
| 304 | * Memory operations - heavily optimized for bandwidth measurement |
| 305 | * Key techniques: |
| 306 | * 1. Multiple independent accumulators to break dependency chains |
| 307 | * 2. Large unrolling (32 elements = 256 bytes per iteration) |
| 308 | * 3. Force inlining to eliminate call overhead |
| 309 | */ |
| 310 | |
| 311 | /* Read operation: XOR all 64-bit words with independent accumulators |
| 312 | * XOR is faster than ADD and has no carry dependency chains */ |
| 313 | static inline __attribute__((always_inline)) |
| 314 | uint64_t mem_read(const void *buf, size_t size) { |
| 315 | const uint64_t *p = (const uint64_t *)buf; |
| 316 | const uint64_t *end = p + (size / sizeof(uint64_t)); |
| 317 | |
| 318 | /* Use 8 independent accumulators - each one handles every 8th element */ |
| 319 | uint64_t x0 = 0, x1 = 0, x2 = 0, x3 = 0; |
| 320 | uint64_t x4 = 0, x5 = 0, x6 = 0, x7 = 0; |
| 321 | |
| 322 | /* Process 32 elements (256 bytes) per iteration */ |
| 323 | while (p + 32 <= end) { |
| 324 | x0 ^= p[0]; x1 ^= p[1]; x2 ^= p[2]; x3 ^= p[3]; |
| 325 | x4 ^= p[4]; x5 ^= p[5]; x6 ^= p[6]; x7 ^= p[7]; |
| 326 | x0 ^= p[8]; x1 ^= p[9]; x2 ^= p[10]; x3 ^= p[11]; |
| 327 | x4 ^= p[12]; x5 ^= p[13]; x6 ^= p[14]; x7 ^= p[15]; |
| 328 | x0 ^= p[16]; x1 ^= p[17]; x2 ^= p[18]; x3 ^= p[19]; |
| 329 | x4 ^= p[20]; x5 ^= p[21]; x6 ^= p[22]; x7 ^= p[23]; |
| 330 | x0 ^= p[24]; x1 ^= p[25]; x2 ^= p[26]; x3 ^= p[27]; |
| 331 | x4 ^= p[28]; x5 ^= p[29]; x6 ^= p[30]; x7 ^= p[31]; |
| 332 | p += 32; |
| 333 | } |
| 334 | |
| 335 | /* Handle remaining elements */ |
| 336 | while (p + 8 <= end) { |
| 337 | x0 ^= p[0]; x1 ^= p[1]; x2 ^= p[2]; x3 ^= p[3]; |
| 338 | x4 ^= p[4]; x5 ^= p[5]; x6 ^= p[6]; x7 ^= p[7]; |
| 339 | p += 8; |
| 340 | } |
| 341 | while (p < end) { |
| 342 | x0 ^= *p++; |
| 343 | } |
| 344 | |
| 345 | return x0 ^ x1 ^ x2 ^ x3 ^ x4 ^ x5 ^ x6 ^ x7; |
| 346 | } |
| 347 | |
| 348 | /* Write operation: fill with pattern, heavily unrolled */ |
| 349 | static inline __attribute__((always_inline)) |
| 350 | void mem_write(void *buf, size_t size, uint64_t pattern) { |
| 351 | uint64_t *p = (uint64_t *)buf; |
| 352 | uint64_t *end = p + (size / sizeof(uint64_t)); |
| 353 | |
| 354 | /* Process 32 elements (256 bytes) per iteration */ |
| 355 | while (p + 32 <= end) { |
| 356 | p[0] = pattern; p[1] = pattern; p[2] = pattern; p[3] = pattern; |
| 357 | p[4] = pattern; p[5] = pattern; p[6] = pattern; p[7] = pattern; |
| 358 | p[8] = pattern; p[9] = pattern; p[10] = pattern; p[11] = pattern; |
| 359 | p[12] = pattern; p[13] = pattern; p[14] = pattern; p[15] = pattern; |
| 360 | p[16] = pattern; p[17] = pattern; p[18] = pattern; p[19] = pattern; |
| 361 | p[20] = pattern; p[21] = pattern; p[22] = pattern; p[23] = pattern; |
| 362 | p[24] = pattern; p[25] = pattern; p[26] = pattern; p[27] = pattern; |
| 363 | p[28] = pattern; p[29] = pattern; p[30] = pattern; p[31] = pattern; |
| 364 | p += 32; |
| 365 | } |
| 366 | |
| 367 | /* Handle remaining */ |
| 368 | while (p < end) { |
| 369 | *p++ = pattern; |
| 370 | } |
| 371 | } |
| 372 | |
| 373 | /* Copy operation: copy from src to dst, heavily unrolled */ |
| 374 | static inline __attribute__((always_inline)) |
| 375 | void mem_copy(void *dst, const void *src, size_t size) { |
| 376 | const uint64_t *s = (const uint64_t *)src; |
| 377 | uint64_t *d = (uint64_t *)dst; |
| 378 | const uint64_t *end = s + (size / sizeof(uint64_t)); |
| 379 | |
| 380 | /* Process 32 elements (256 bytes) per iteration */ |
| 381 | while (s + 32 <= end) { |
| 382 | d[0] = s[0]; d[1] = s[1]; d[2] = s[2]; d[3] = s[3]; |
| 383 | d[4] = s[4]; d[5] = s[5]; d[6] = s[6]; d[7] = s[7]; |
| 384 | d[8] = s[8]; d[9] = s[9]; d[10] = s[10]; d[11] = s[11]; |
| 385 | d[12] = s[12]; d[13] = s[13]; d[14] = s[14]; d[15] = s[15]; |
| 386 | d[16] = s[16]; d[17] = s[17]; d[18] = s[18]; d[19] = s[19]; |
| 387 | d[20] = s[20]; d[21] = s[21]; d[22] = s[22]; d[23] = s[23]; |
| 388 | d[24] = s[24]; d[25] = s[25]; d[26] = s[26]; d[27] = s[27]; |
| 389 | d[28] = s[28]; d[29] = s[29]; d[30] = s[30]; d[31] = s[31]; |
| 390 | s += 32; |
| 391 | d += 32; |
| 392 | } |
| 393 | |
| 394 | /* Handle remaining */ |
| 395 | while (s < end) { |
| 396 | *d++ = *s++; |
| 397 | } |
| 398 | } |
| 399 | |
| 400 | /* |
| 401 | * Memory latency test using pointer chasing |
| 402 | * |
| 403 | * This implementation is based on ram_bench by Emil Ernerfeldt: |
| 404 | * https://github.com/emilk/ram_bench |
| 405 | * |
| 406 | * Recommended by Alex Miller. |
| 407 | * |
| 408 | * Uses a linked list traversal approach where each node contains a payload |
| 409 | * and a pointer to the next node. Nodes are allocated contiguously but |
| 410 | * linked in random order to defeat hardware prefetchers. |
| 411 | * |
| 412 | * Key insight from ram_bench: random memory access cost is O(√N) due to |
| 413 | * cache hierarchy (L1, L2, L3, RAM) and the fundamental limit that memory |
| 414 | * within distance r from CPU is bounded by r² (Bekenstein bound). |
| 415 | */ |
| 416 | |
| 417 | /* Node structure for linked list traversal (16 bytes like ram_bench) |
| 418 | * The payload prevents compiler from optimizing away the traversal |
| 419 | * and makes the structure cache-line realistic */ |
| 420 | typedef struct LatencyNode LatencyNode; |
| 421 | struct LatencyNode { |
| 422 | uint64_t payload; /* Dummy data for realistic cache behavior */ |
| 423 | LatencyNode *next; /* Pointer to next node in chain */ |
| 424 | }; |
| 425 | |
| 426 | /* Statistical parameters for latency measurement */ |
| 427 | #define LATENCY_MIN_SAMPLES 7 /* Minimum samples for statistical validity */ |
| 428 | #define LATENCY_MAX_SAMPLES 21 /* Maximum samples (enough for robust statistics) */ |
| 429 | #define LATENCY_TARGET_CV 0.05 /* Target coefficient of variation (5%) */ |
| 430 | |
| 431 | /* Comparison function for qsort (double ascending) */ |
| 432 | static int compare_double(const void *a, const void *b) { |
| 433 | double da = *(const double *)a; |
| 434 | double db = *(const double *)b; |
| 435 | if (da < db) return -1; |
| 436 | if (da > db) return 1; |
| 437 | return 0; |
| 438 | } |
| 439 | |
| 440 | /* Calculate median of sorted array */ |
| 441 | static double calculate_median(double *sorted, int n) { |
| 442 | if (n == 0) return 0; |
| 443 | if (n % 2 == 0) { |
| 444 | return (sorted[n/2 - 1] + sorted[n/2]) / 2.0; |
| 445 | } |
| 446 | return sorted[n/2]; |
| 447 | } |
| 448 | |
| 449 | /* Calculate mean of array */ |
| 450 | static double calculate_mean(double *arr, int n) { |
| 451 | if (n == 0) return 0; |
| 452 | double sum = 0; |
| 453 | for (int i = 0; i < n; i++) { |
| 454 | sum += arr[i]; |
| 455 | } |
| 456 | return sum / n; |
| 457 | } |
| 458 | |
| 459 | /* Calculate standard deviation of array */ |
| 460 | static double calculate_stddev(double *arr, int n, double mean) { |
| 461 | if (n < 2) return 0; |
| 462 | double sum_sq = 0; |
| 463 | for (int i = 0; i < n; i++) { |
| 464 | double diff = arr[i] - mean; |
| 465 | sum_sq += diff * diff; |
| 466 | } |
| 467 | return sqrt(sum_sq / (n - 1)); /* Sample standard deviation */ |
| 468 | } |
| 469 | |
| 470 | /* Fisher-Yates shuffle for node pointer array */ |
| 471 | static void shuffle_nodes(LatencyNode **nodes, size_t n) { |
| 472 | for (size_t i = n - 1; i > 0; i--) { |
| 473 | size_t j = (size_t)rand() % (i + 1); |
| 474 | LatencyNode *tmp = nodes[i]; |
| 475 | nodes[i] = nodes[j]; |
| 476 | nodes[j] = tmp; |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | /* Allocate memory for latency chain with NUMA awareness and huge page support |
| 481 | * Uses mmap with optional huge pages to reduce TLB overhead for large buffers */ |
| 482 | static LatencyNode* alloc_latency_memory(size_t num_nodes, size_t *alloc_size) { |
| 483 | size_t size = num_nodes * sizeof(LatencyNode); |
| 484 | *alloc_size = size; |
| 485 | |
| 486 | LatencyNode *memory = MAP_FAILED; |
| 487 | int try_hugepages = g_use_hugepages && (size >= get_huge_page_threshold()); |
| 488 | |
| 489 | if (try_hugepages) { |
| 490 | /* Round up size to huge page boundary */ |
| 491 | size_t hp_size = get_huge_page_size(); |
| 492 | size_t aligned_size = (size + hp_size - 1) & ~(hp_size - 1); |
| 493 | *alloc_size = aligned_size; |
| 494 | |
| 495 | #ifdef MAP_HUGETLB |
| 496 | /* Try explicit huge pages first */ |
| 497 | memory = (LatencyNode *)mmap(NULL, aligned_size, PROT_READ | PROT_WRITE, |
| 498 | MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0); |
| 499 | if (memory != MAP_FAILED) { |
| 500 | if (g_verbose >= 2) { |
| 501 | fprintf(stderr, " Latency: allocated %zu bytes using explicit 2MB huge pages\n", aligned_size); |
| 502 | } |
| 503 | } |
| 504 | #endif |
| 505 | |
| 506 | /* Fall back to THP (Transparent Huge Pages) */ |
| 507 | if (memory == MAP_FAILED) { |
| 508 | memory = (LatencyNode *)mmap(NULL, size, PROT_READ | PROT_WRITE, |
| 509 | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); |
| 510 | if (memory != MAP_FAILED) { |
| 511 | #ifdef MADV_HUGEPAGE |
| 512 | if (madvise(memory, size, MADV_HUGEPAGE) == 0) { |
| 513 | if (g_verbose >= 2) { |
| 514 | fprintf(stderr, " Latency: allocated %zu bytes with THP (transparent huge pages)\n", size); |
| 515 | } |
| 516 | } else if (g_verbose >= 2) { |
| 517 | fprintf(stderr, " Latency: allocated %zu bytes (THP hint failed)\n", size); |
| 518 | } |
| 519 | #endif |
| 520 | *alloc_size = size; /* Reset to actual size for THP */ |
| 521 | } |
| 522 | } |
| 523 | } |
| 524 | |
| 525 | /* Regular allocation if huge pages disabled or failed */ |
| 526 | if (memory == MAP_FAILED) { |
| 527 | memory = (LatencyNode *)mmap(NULL, size, PROT_READ | PROT_WRITE, |
| 528 | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); |
| 529 | *alloc_size = size; |
| 530 | } |
| 531 | |
| 532 | if (memory == MAP_FAILED) return NULL; |
| 533 | |
| 534 | #ifdef USE_NUMA |
| 535 | /* Bind memory to NUMA node 0 (where CPU 0 is) for consistent latency measurement */ |
| 536 | if (numa_available() >= 0 && g_numa_nodes > 1) { |
| 537 | int node = numa_node_of_cpu(0); |
| 538 | if (node >= 0) { |
| 539 | unsigned long nodemask = 1UL << node; |
| 540 | mbind(memory, *alloc_size, MPOL_BIND, &nodemask, g_numa_nodes + 1, MPOL_MF_MOVE); |
| 541 | if (g_verbose >= 2) { |
| 542 | fprintf(stderr, " Latency memory bound to NUMA node %d\n", node); |
| 543 | } |
| 544 | } |
| 545 | } |
| 546 | #endif |
| 547 | |
| 548 | return memory; |
| 549 | } |
| 550 | |
| 551 | /* Free latency chain memory allocated via mmap */ |
| 552 | static void free_latency_memory(LatencyNode *memory, size_t alloc_size) { |
| 553 | if (memory && alloc_size > 0) { |
| 554 | munmap(memory, alloc_size); |
| 555 | } |
| 556 | } |
| 557 | |
| 558 | /* Initialize linked list with random traversal order |
| 559 | * Memory is contiguous (good for allocation) but traversal is random |
| 560 | * (defeats prefetcher, measures true memory latency) |
| 561 | * Returns: start node pointer; caller must track alloc_size for freeing */ |
| 562 | static LatencyNode* init_latency_chain(size_t num_nodes, size_t *alloc_size) { |
| 563 | if (num_nodes < 2) return NULL; |
| 564 | |
| 565 | /* Allocate contiguous memory for all nodes using NUMA-aware allocation */ |
| 566 | LatencyNode *memory = alloc_latency_memory(num_nodes, alloc_size); |
| 567 | if (!memory) return NULL; |
| 568 | |
| 569 | /* Initialize payloads (also touches pages for NUMA first-touch policy) */ |
| 570 | for (size_t i = 0; i < num_nodes; i++) { |
| 571 | memory[i].payload = i; /* Unique payload for each node */ |
| 572 | } |
| 573 | |
| 574 | /* Create array of pointers for shuffling */ |
| 575 | LatencyNode **nodes = (LatencyNode **)malloc(num_nodes * sizeof(LatencyNode *)); |
| 576 | if (!nodes) { |
| 577 | free_latency_memory(memory, *alloc_size); |
| 578 | return NULL; |
| 579 | } |
| 580 | |
| 581 | for (size_t i = 0; i < num_nodes; i++) { |
| 582 | nodes[i] = &memory[i]; |
| 583 | } |
| 584 | |
| 585 | /* Shuffle to create random traversal order */ |
| 586 | shuffle_nodes(nodes, num_nodes); |
| 587 | |
| 588 | /* Link nodes in shuffled order (circular) */ |
| 589 | for (size_t i = 0; i < num_nodes - 1; i++) { |
| 590 | nodes[i]->next = nodes[i + 1]; |
| 591 | } |
| 592 | nodes[num_nodes - 1]->next = nodes[0]; /* Close the loop */ |
| 593 | |
| 594 | LatencyNode *start = nodes[0]; |
| 595 | free(nodes); |
| 596 | |
| 597 | return start; |
| 598 | } |
| 599 | |
| 600 | /* Free latency chain - need base address and size */ |
| 601 | static void free_latency_chain(LatencyNode *start, size_t num_nodes, size_t alloc_size) { |
| 602 | if (!start || num_nodes == 0) return; |
| 603 | |
| 604 | /* Find the lowest address in the chain (that's where mmap'd block starts) */ |
| 605 | LatencyNode *min_addr = start; |
| 606 | LatencyNode *node = start->next; |
| 607 | size_t visited = 1; |
| 608 | while (node != start && visited < num_nodes) { |
| 609 | if (node < min_addr) min_addr = node; |
| 610 | node = node->next; |
| 611 | visited++; |
| 612 | } |
| 613 | |
| 614 | free_latency_memory(min_addr, alloc_size); |
| 615 | } |
| 616 | |
| 617 | /* Pin current thread to CPU 0 for consistent latency measurement. |
| 618 | * Platform-specific implementations for Linux, macOS, and BSD. */ |
| 619 | static void pin_thread_to_cpu0(void) { |
| 620 | int success = 0; |
| 621 | |
| 622 | #ifdef PLATFORM_LINUX |
| 623 | cpu_set_t cpuset; |
| 624 | CPU_ZERO(&cpuset); |
| 625 | CPU_SET(0, &cpuset); |
| 626 | success = (sched_setaffinity(0, sizeof(cpu_set_t), &cpuset) == 0); |
| 627 | #endif |
| 628 | |
| 629 | #ifdef PLATFORM_BSD |
| 630 | cpuset_t cpuset; |
| 631 | CPU_ZERO(&cpuset); |
| 632 | CPU_SET(0, &cpuset); |
| 633 | success = (cpuset_setaffinity(CPU_LEVEL_WHICH, CPU_WHICH_TID, -1, |
| 634 | sizeof(cpuset), &cpuset) == 0); |
| 635 | #endif |
| 636 | |
| 637 | #ifdef PLATFORM_MACOS |
| 638 | /* macOS doesn't have true CPU affinity, but we can suggest affinity |
| 639 | * via thread_policy_set with THREAD_AFFINITY_POLICY. |
| 640 | * This is a hint, not a guarantee. */ |
| 641 | thread_affinity_policy_data_t policy = { 0 }; /* Affinity tag 0 */ |
| 642 | success = (thread_policy_set(mach_thread_self(), THREAD_AFFINITY_POLICY, |
| 643 | (thread_policy_t)&policy, |
| 644 | THREAD_AFFINITY_POLICY_COUNT) == KERN_SUCCESS); |
| 645 | #endif |
| 646 | |
| 647 | if (g_verbose >= 2) { |
| 648 | if (success) { |
| 649 | fprintf(stderr, " Latency thread pinned to CPU 0\n"); |
| 650 | } else { |
| 651 | fprintf(stderr, " Warning: Could not pin thread to CPU 0\n"); |
| 652 | } |
| 653 | } |
| 654 | (void)success; /* Suppress unused warning if no platform matched */ |
| 655 | } |
| 656 | |
| 657 | /* Chase through linked list - each load depends on previous |
| 658 | * Returns final node pointer to prevent optimization */ |
| 659 | static inline __attribute__((always_inline)) |
| 660 | LatencyNode* chase_latency_chain(LatencyNode *start, size_t count) { |
| 661 | LatencyNode *node = start; |
| 662 | volatile uint64_t sink = 0; /* Prevent optimization */ |
| 663 | |
| 664 | /* Unroll 8x to reduce loop overhead while maintaining dependency chain */ |
| 665 | size_t i = count; |
| 666 | while (i >= 8) { |
| 667 | sink += node->payload; node = node->next; |
| 668 | sink += node->payload; node = node->next; |
| 669 | sink += node->payload; node = node->next; |
| 670 | sink += node->payload; node = node->next; |
| 671 | sink += node->payload; node = node->next; |
| 672 | sink += node->payload; node = node->next; |
| 673 | sink += node->payload; node = node->next; |
| 674 | sink += node->payload; node = node->next; |
| 675 | i -= 8; |
| 676 | } |
| 677 | while (i > 0) { |
| 678 | sink += node->payload; |
| 679 | node = node->next; |
| 680 | i--; |
| 681 | } |
| 682 | |
| 683 | g_sink += sink; /* Store to global to prevent optimization */ |
| 684 | return node; |
| 685 | } |
| 686 | |
| 687 | /* Result structure for latency measurement with statistics */ |
| 688 | typedef struct { |
| 689 | double median_ns; /* Median latency (robust to outliers) */ |
| 690 | double mean_ns; /* Mean latency */ |
| 691 | double stddev_ns; /* Standard deviation */ |
| 692 | double cv; /* Coefficient of variation (stddev/mean) */ |
| 693 | int num_samples; /* Number of samples collected */ |
| 694 | size_t total_accesses; /* Total node accesses performed */ |
| 695 | } latency_stats_t; |
| 696 | |
| 697 | /* Target time per sample in seconds - long enough for timer precision, |
| 698 | * short enough for reasonable total measurement time */ |
| 699 | #define LATENCY_TARGET_SAMPLE_TIME 0.1 /* 100ms per sample */ |
| 700 | #define LATENCY_MIN_SAMPLE_TIME 0.01 /* 10ms minimum for timer precision */ |
| 701 | |
| 702 | /* Measure latency with statistical validity |
| 703 | * |
| 704 | * Strategy: |
| 705 | * 1. Create random linked list covering the buffer size |
| 706 | * 2. Warmup by traversing the list once |
| 707 | * 3. Calibration run to estimate latency and calculate traversals needed |
| 708 | * 4. Collect multiple independent time samples |
| 709 | * 5. Continue until CV < target or max samples reached |
| 710 | * 6. Report median (robust to outliers) and statistics |
| 711 | * |
| 712 | * Returns statistically valid latency measurement |
| 713 | */ |
| 714 | static latency_stats_t measure_latency_stats(size_t buffer_size) { |
| 715 | latency_stats_t stats = {0}; |
| 716 | |
| 717 | /* Pin thread to CPU 0 for consistent latency measurement. |
| 718 | * This prevents OS scheduler from migrating the thread during measurement, |
| 719 | * which would cause inconsistent results due to cache effects and NUMA. */ |
| 720 | pin_thread_to_cpu0(); |
| 721 | |
| 722 | /* Calculate number of nodes that fit in buffer */ |
| 723 | size_t num_nodes = buffer_size / sizeof(LatencyNode); |
| 724 | if (num_nodes < 64) num_nodes = 64; /* Minimum for meaningful measurement */ |
| 725 | |
| 726 | /* Initialize chain with NUMA-aware allocation */ |
| 727 | size_t alloc_size = 0; |
| 728 | LatencyNode *start = init_latency_chain(num_nodes, &alloc_size); |
| 729 | if (!start) { |
| 730 | fprintf(stderr, "Failed to allocate %zu bytes for latency test\n", |
| 731 | num_nodes * sizeof(LatencyNode)); |
| 732 | return stats; |
| 733 | } |
| 734 | |
| 735 | /* Warmup: single traversal to prime caches and stabilize CPU */ |
| 736 | chase_latency_chain(start, num_nodes); |
| 737 | |
| 738 | /* Calibration: time a single traversal to estimate latency */ |
| 739 | double cal_start = get_time(); |
| 740 | chase_latency_chain(start, num_nodes); |
| 741 | double cal_elapsed = get_time() - cal_start; |
| 742 | |
| 743 | /* Calculate traversals needed to achieve target sample time */ |
| 744 | double estimated_latency_s = cal_elapsed / num_nodes; |
| 745 | size_t traversals_per_sample; |
| 746 | |
| 747 | if (estimated_latency_s > 0) { |
| 748 | /* Calculate traversals to reach target sample time */ |
| 749 | double target_accesses = LATENCY_TARGET_SAMPLE_TIME / estimated_latency_s; |
| 750 | traversals_per_sample = (size_t)(target_accesses / num_nodes); |
| 751 | |
| 752 | /* Ensure at least 1 full traversal per sample */ |
| 753 | if (traversals_per_sample < 1) traversals_per_sample = 1; |
| 754 | |
| 755 | /* Cap at reasonable maximum for very fast (L1) accesses */ |
| 756 | if (traversals_per_sample > 10000) traversals_per_sample = 10000; |
| 757 | } else { |
| 758 | /* Fallback: at least 1 traversal */ |
| 759 | traversals_per_sample = 1; |
| 760 | } |
| 761 | |
| 762 | /* Sample collection */ |
| 763 | double samples[LATENCY_MAX_SAMPLES]; |
| 764 | int num_samples = 0; |
| 765 | size_t total_accesses = 0; |
| 766 | |
| 767 | /* Collect samples until statistically valid or max reached */ |
| 768 | while (num_samples < LATENCY_MAX_SAMPLES) { |
| 769 | size_t accesses_this_sample = num_nodes * traversals_per_sample; |
| 770 | |
| 771 | /* Time this sample */ |
| 772 | double start_time = get_time(); |
| 773 | chase_latency_chain(start, accesses_this_sample); |
| 774 | double end_time = get_time(); |
| 775 | |
| 776 | double elapsed = end_time - start_time; |
| 777 | double latency_ns = (elapsed * 1e9) / accesses_this_sample; |
| 778 | |
| 779 | samples[num_samples++] = latency_ns; |
| 780 | total_accesses += accesses_this_sample; |
| 781 | |
| 782 | /* Check if we have enough samples and they're stable */ |
| 783 | if (num_samples >= LATENCY_MIN_SAMPLES) { |
| 784 | double mean = calculate_mean(samples, num_samples); |
| 785 | double stddev = calculate_stddev(samples, num_samples, mean); |
| 786 | double cv = (mean > 0) ? (stddev / mean) : 1.0; |
| 787 | |
| 788 | /* Stop if coefficient of variation is acceptable */ |
| 789 | if (cv < LATENCY_TARGET_CV) { |
| 790 | break; |
| 791 | } |
| 792 | } |
| 793 | } |
| 794 | |
| 795 | /* Calculate final statistics */ |
| 796 | double mean = calculate_mean(samples, num_samples); |
| 797 | double stddev = calculate_stddev(samples, num_samples, mean); |
| 798 | |
| 799 | /* Sort for median calculation */ |
| 800 | qsort(samples, num_samples, sizeof(double), compare_double); |
| 801 | double median = calculate_median(samples, num_samples); |
| 802 | |
| 803 | /* Populate result */ |
| 804 | stats.median_ns = median; |
| 805 | stats.mean_ns = mean; |
| 806 | stats.stddev_ns = stddev; |
| 807 | stats.cv = (mean > 0) ? (stddev / mean) : 0; |
| 808 | stats.num_samples = num_samples; |
| 809 | stats.total_accesses = total_accesses; |
| 810 | |
| 811 | /* Cleanup */ |
| 812 | free_latency_chain(start, num_nodes, alloc_size); |
| 813 | |
| 814 | return stats; |
| 815 | } |
| 816 | |
| 817 | /* ============================================================================ |
| 818 | * Memory allocation |
| 819 | * ============================================================================ */ |
| 820 | |
| 821 | static void* alloc_buffer(size_t size) { |
| 822 | void *buf = MAP_FAILED; |
| 823 | int try_hugepages = g_use_hugepages && (size >= get_huge_page_threshold()); |
| 824 | |
| 825 | if (try_hugepages) { |
| 826 | /* |
| 827 | * Strategy: prefer THP over explicit huge pages because: |
| 828 | * 1. THP doesn't require pre-allocation by root |
| 829 | * 2. THP is managed automatically by the kernel |
| 830 | * 3. Explicit huge pages may fail if pool isn't configured |
| 831 | * |
| 832 | * We try explicit huge pages first only because they're more |
| 833 | * deterministic (guaranteed 2MB pages vs THP's best-effort). |
| 834 | */ |
| 835 | |
| 836 | #ifdef MAP_HUGETLB |
| 837 | /* Round up size to huge page boundary for explicit huge pages */ |
| 838 | size_t hp_size = get_huge_page_size(); |
| 839 | size_t aligned_size = (size + hp_size - 1) & ~(hp_size - 1); |
| 840 | |
| 841 | /* Try explicit huge pages (uses pre-allocated pool if available) */ |
| 842 | buf = mmap(NULL, aligned_size, PROT_READ | PROT_WRITE, |
| 843 | MAP_PRIVATE | MAP_ANONYMOUS | MAP_HUGETLB, -1, 0); |
| 844 | if (buf != MAP_FAILED) { |
| 845 | if (g_verbose >= 2) { |
| 846 | fprintf(stderr, " Allocated %zu bytes using explicit %zu KB huge pages\n", |
| 847 | aligned_size, hp_size / 1024); |
| 848 | } |
| 849 | /* Touch all pages to ensure they're allocated */ |
| 850 | memset(buf, 0, size); |
| 851 | return buf; |
| 852 | } |
| 853 | /* Explicit huge pages failed - likely no pool configured, try THP */ |
| 854 | #endif |
| 855 | |
| 856 | /* Use mmap + madvise for Transparent Huge Pages (no pre-allocation needed) */ |
| 857 | buf = mmap(NULL, size, PROT_READ | PROT_WRITE, |
| 858 | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); |
| 859 | if (buf != MAP_FAILED) { |
| 860 | #ifdef MADV_HUGEPAGE |
| 861 | /* Hint to kernel: please use huge pages for this region. |
| 862 | * The kernel will use THP if available and beneficial. |
| 863 | * This doesn't require root or pre-allocation. */ |
| 864 | if (madvise(buf, size, MADV_HUGEPAGE) == 0) { |
| 865 | if (g_verbose >= 2) { |
| 866 | fprintf(stderr, " Allocated %zu bytes with THP (transparent huge pages)\n", size); |
| 867 | } |
| 868 | } else if (g_verbose >= 2) { |
| 869 | fprintf(stderr, " Allocated %zu bytes (THP hint failed, using regular pages)\n", size); |
| 870 | } |
| 871 | #else |
| 872 | if (g_verbose >= 2) { |
| 873 | fprintf(stderr, " Allocated %zu bytes (THP not available on this system)\n", size); |
| 874 | } |
| 875 | #endif |
| 876 | /* Touch all pages to ensure they're allocated */ |
| 877 | memset(buf, 0, size); |
| 878 | return buf; |
| 879 | } |
| 880 | } |
| 881 | |
| 882 | /* Regular allocation: small buffers, huge pages disabled, or fallback */ |
| 883 | buf = mmap(NULL, size, PROT_READ | PROT_WRITE, |
| 884 | MAP_PRIVATE | MAP_ANONYMOUS, -1, 0); |
| 885 | |
| 886 | if (buf == MAP_FAILED) { |
| 887 | return NULL; |
| 888 | } |
| 889 | |
| 890 | /* Touch all pages to ensure they're allocated */ |
| 891 | memset(buf, 0, size); |
| 892 | |
| 893 | return buf; |
| 894 | } |
| 895 | |
| 896 | static void free_buffer(void *buf, size_t size) { |
| 897 | if (buf) { |
| 898 | munmap(buf, size); |
| 899 | } |
| 900 | } |
| 901 | |
| 902 | /* ============================================================================ |
| 903 | * Cache topology detection using hwloc (portable: x86, arm64, etc.) |
| 904 | * |
| 905 | * Install hwloc: |
| 906 | * Debian/Ubuntu: apt-get install libhwloc-dev |
| 907 | * RHEL/CentOS: yum install hwloc-devel |
| 908 | * macOS: brew install hwloc |
| 909 | * ============================================================================ */ |
| 910 | |
| 911 | #ifdef USE_HWLOC |
| 912 | #include <hwloc.h> |
| 913 | |
| 914 | static hwloc_topology_t g_topology = NULL; |
| 915 | |
| 916 | /* Detect cache sizes using hwloc */ |
| 917 | static void init_cache_info(void) { |
| 918 | if (hwloc_topology_init(&g_topology) < 0) { |
| 919 | goto use_defaults; |
| 920 | } |
| 921 | |
| 922 | if (hwloc_topology_load(g_topology) < 0) { |
| 923 | hwloc_topology_destroy(g_topology); |
| 924 | g_topology = NULL; |
| 925 | goto use_defaults; |
| 926 | } |
| 927 | |
| 928 | /* Find cache sizes by iterating through cache objects */ |
| 929 | int depth; |
| 930 | |
| 931 | /* L1 Data Cache */ |
| 932 | depth = hwloc_get_type_depth(g_topology, HWLOC_OBJ_L1CACHE); |
| 933 | if (depth != HWLOC_TYPE_DEPTH_UNKNOWN) { |
| 934 | hwloc_obj_t obj = hwloc_get_obj_by_depth(g_topology, depth, 0); |
| 935 | if (obj && obj->attr && obj->attr->cache.type != HWLOC_OBJ_CACHE_INSTRUCTION) { |
| 936 | g_l1_cache_size = obj->attr->cache.size; |
| 937 | } |
| 938 | } |
| 939 | |
| 940 | /* L2 Cache */ |
| 941 | depth = hwloc_get_type_depth(g_topology, HWLOC_OBJ_L2CACHE); |
| 942 | if (depth != HWLOC_TYPE_DEPTH_UNKNOWN) { |
| 943 | hwloc_obj_t obj = hwloc_get_obj_by_depth(g_topology, depth, 0); |
| 944 | if (obj && obj->attr) { |
| 945 | g_l2_cache_size = obj->attr->cache.size; |
| 946 | } |
| 947 | } |
| 948 | |
| 949 | /* L3 Cache */ |
| 950 | depth = hwloc_get_type_depth(g_topology, HWLOC_OBJ_L3CACHE); |
| 951 | if (depth != HWLOC_TYPE_DEPTH_UNKNOWN) { |
| 952 | hwloc_obj_t obj = hwloc_get_obj_by_depth(g_topology, depth, 0); |
| 953 | if (obj && obj->attr) { |
| 954 | g_l3_cache_size = obj->attr->cache.size; |
| 955 | } |
| 956 | } |
| 957 | |
| 958 | /* Count total L3 cache (sum across all L3 objects for distributed caches) */ |
| 959 | if (g_l3_cache_size > 0) { |
| 960 | depth = hwloc_get_type_depth(g_topology, HWLOC_OBJ_L3CACHE); |
| 961 | int num_l3 = hwloc_get_nbobjs_by_depth(g_topology, depth); |
| 962 | if (g_verbose && num_l3 > 1) { |
| 963 | fprintf(stderr, "Note: %d L3 caches detected (distributed across dies)\n", num_l3); |
| 964 | } |
| 965 | } |
| 966 | |
| 967 | use_defaults: |
| 968 | /* Set defaults if detection failed */ |
| 969 | if (g_l1_cache_size == 0) g_l1_cache_size = 32 * 1024; /* 32 KB */ |
| 970 | if (g_l2_cache_size == 0) g_l2_cache_size = 256 * 1024; /* 256 KB */ |
| 971 | if (g_l3_cache_size == 0) g_l3_cache_size = 8 * 1024 * 1024; /* 8 MB */ |
| 972 | |
| 973 | /* Calculate adaptive minimum total size: |
| 974 | * Use 16KB per thread × num_cpus so each thread has a reliable buffer size. |
| 975 | * This ensures all CPUs can participate with meaningful measurements. */ |
| 976 | g_min_total_size = 16384 * g_num_cpus; /* 16KB per thread minimum */ |
| 977 | |
| 978 | if (g_verbose) { |
| 979 | fprintf(stderr, "Cache (hwloc): L1d=%zuKB, L2=%zuKB, L3=%zuKB (per core)\n", |
| 980 | g_l1_cache_size / 1024, g_l2_cache_size / 1024, g_l3_cache_size / 1024); |
| 981 | fprintf(stderr, "Minimum total test size: %zu KB (16KB × %d CPUs)\n", |
| 982 | g_min_total_size / 1024, g_num_cpus); |
| 983 | } |
| 984 | } |
| 985 | |
| 986 | static void cleanup_hwloc(void) { |
| 987 | if (g_topology) { |
| 988 | hwloc_topology_destroy(g_topology); |
| 989 | g_topology = NULL; |
| 990 | } |
| 991 | } |
| 992 | |
| 993 | #else /* !USE_HWLOC - fallback to platform-specific methods */ |
| 994 | |
| 995 | #ifdef PLATFORM_LINUX |
| 996 | /* Parse cache size from sysfs (handles "48K", "1024K", "32768K" format) */ |
| 997 | static size_t parse_cache_size_sysfs(const char *str) { |
| 998 | size_t size = 0; |
| 999 | char unit = 0; |
| 1000 | if (sscanf(str, "%zu%c", &size, &unit) >= 1) { |
| 1001 | if (unit == 'K' || unit == 'k') size *= 1024; |
| 1002 | else if (unit == 'M' || unit == 'm') size *= 1024 * 1024; |
| 1003 | } |
| 1004 | return size; |
| 1005 | } |
| 1006 | |
| 1007 | /* Read cache info from sysfs (Linux-specific) */ |
| 1008 | static void init_cache_info_linux(void) { |
| 1009 | char path[256]; |
| 1010 | char buf[64]; |
| 1011 | FILE *f; |
| 1012 | |
| 1013 | for (int index = 0; index < 10; index++) { |
| 1014 | /* Read level */ |
| 1015 | snprintf(path, sizeof(path), |
| 1016 | "/sys/devices/system/cpu/cpu0/cache/index%d/level", index); |
| 1017 | f = fopen(path, "r"); |
| 1018 | if (!f) continue; |
| 1019 | int level = -1; |
| 1020 | if (fgets(buf, sizeof(buf), f)) level = atoi(buf); |
| 1021 | fclose(f); |
| 1022 | if (level < 0) continue; |
| 1023 | |
| 1024 | /* Read type */ |
| 1025 | snprintf(path, sizeof(path), |
| 1026 | "/sys/devices/system/cpu/cpu0/cache/index%d/type", index); |
| 1027 | f = fopen(path, "r"); |
| 1028 | if (!f) continue; |
| 1029 | char type[32] = ""; |
| 1030 | if (fgets(type, sizeof(type), f)) type[strcspn(type, "\n")] = 0; |
| 1031 | fclose(f); |
| 1032 | |
| 1033 | /* Skip instruction caches */ |
| 1034 | if (strcmp(type, "Instruction") == 0) continue; |
| 1035 | |
| 1036 | /* Read size */ |
| 1037 | snprintf(path, sizeof(path), |
| 1038 | "/sys/devices/system/cpu/cpu0/cache/index%d/size", index); |
| 1039 | f = fopen(path, "r"); |
| 1040 | if (!f) continue; |
| 1041 | size_t size = 0; |
| 1042 | if (fgets(buf, sizeof(buf), f)) size = parse_cache_size_sysfs(buf); |
| 1043 | fclose(f); |
| 1044 | |
| 1045 | if (size == 0) continue; |
| 1046 | |
| 1047 | switch (level) { |
| 1048 | case 1: if (g_l1_cache_size == 0) g_l1_cache_size = size; break; |
| 1049 | case 2: if (g_l2_cache_size == 0) g_l2_cache_size = size; break; |
| 1050 | case 3: if (g_l3_cache_size == 0) g_l3_cache_size = size; break; |
| 1051 | } |
| 1052 | } |
| 1053 | } |
| 1054 | #endif /* PLATFORM_LINUX */ |
| 1055 | |
| 1056 | #ifdef PLATFORM_MACOS |
| 1057 | /* Read cache info from sysctl (macOS-specific) */ |
| 1058 | static void init_cache_info_macos(void) { |
| 1059 | size_t size; |
| 1060 | size_t len = sizeof(size); |
| 1061 | |
| 1062 | /* L1 data cache */ |
| 1063 | if (sysctlbyname("hw.l1dcachesize", &size, &len, NULL, 0) == 0 && size > 0) { |
| 1064 | g_l1_cache_size = size; |
| 1065 | } |
| 1066 | |
| 1067 | /* L2 cache */ |
| 1068 | len = sizeof(size); |
| 1069 | if (sysctlbyname("hw.l2cachesize", &size, &len, NULL, 0) == 0 && size > 0) { |
| 1070 | g_l2_cache_size = size; |
| 1071 | } |
| 1072 | |
| 1073 | /* L3 cache (may not exist on all Macs) */ |
| 1074 | len = sizeof(size); |
| 1075 | if (sysctlbyname("hw.l3cachesize", &size, &len, NULL, 0) == 0 && size > 0) { |
| 1076 | g_l3_cache_size = size; |
| 1077 | } |
| 1078 | } |
| 1079 | #endif /* PLATFORM_MACOS */ |
| 1080 | |
| 1081 | #ifdef PLATFORM_BSD |
| 1082 | /* Read cache info from sysctl (BSD-specific) */ |
| 1083 | static void init_cache_info_bsd(void) { |
| 1084 | /* FreeBSD and other BSDs have limited sysctl cache info. |
| 1085 | * Try standard hw.cacheXXX values, fall back to defaults. */ |
| 1086 | size_t size; |
| 1087 | size_t len = sizeof(size); |
| 1088 | |
| 1089 | /* Try various BSD sysctl names */ |
| 1090 | if (sysctlbyname("hw.l1dcachesize", &size, &len, NULL, 0) == 0 && size > 0) { |
| 1091 | g_l1_cache_size = size; |
| 1092 | } |
| 1093 | len = sizeof(size); |
| 1094 | if (sysctlbyname("hw.l2cachesize", &size, &len, NULL, 0) == 0 && size > 0) { |
| 1095 | g_l2_cache_size = size; |
| 1096 | } |
| 1097 | len = sizeof(size); |
| 1098 | if (sysctlbyname("hw.l3cachesize", &size, &len, NULL, 0) == 0 && size > 0) { |
| 1099 | g_l3_cache_size = size; |
| 1100 | } |
| 1101 | } |
| 1102 | #endif /* PLATFORM_BSD */ |
| 1103 | |
| 1104 | /* Platform-agnostic cache info initialization */ |
| 1105 | static void init_cache_info(void) { |
| 1106 | const char *method = "defaults"; |
| 1107 | |
| 1108 | #ifdef PLATFORM_LINUX |
| 1109 | init_cache_info_linux(); |
| 1110 | method = "sysfs"; |
| 1111 | #endif |
| 1112 | |
| 1113 | #ifdef PLATFORM_MACOS |
| 1114 | init_cache_info_macos(); |
| 1115 | method = "sysctl"; |
| 1116 | #endif |
| 1117 | |
| 1118 | #ifdef PLATFORM_BSD |
| 1119 | init_cache_info_bsd(); |
| 1120 | method = "sysctl"; |
| 1121 | #endif |
| 1122 | |
| 1123 | /* Set defaults if detection failed */ |
| 1124 | if (g_l1_cache_size == 0) g_l1_cache_size = 32 * 1024; /* 32 KB */ |
| 1125 | if (g_l2_cache_size == 0) g_l2_cache_size = 256 * 1024; /* 256 KB */ |
| 1126 | if (g_l3_cache_size == 0) g_l3_cache_size = 8 * 1024 * 1024; /* 8 MB */ |
| 1127 | |
| 1128 | /* Calculate adaptive minimum total size: |
| 1129 | * Use 16KB per thread × num_cpus so each thread has a reliable buffer size. */ |
| 1130 | g_min_total_size = 16384 * g_num_cpus; /* 16KB per thread minimum */ |
| 1131 | |
| 1132 | if (g_verbose) { |
| 1133 | fprintf(stderr, "Cache (%s): L1d=%zuKB, L2=%zuKB, L3=%zuKB (per core)\n", |
| 1134 | method, g_l1_cache_size / 1024, g_l2_cache_size / 1024, |
| 1135 | g_l3_cache_size / 1024); |
| 1136 | fprintf(stderr, "Minimum total test size: %zu KB (16KB × %d CPUs)\n", |
| 1137 | g_min_total_size / 1024, g_num_cpus); |
| 1138 | } |
| 1139 | } |
| 1140 | |
| 1141 | static void cleanup_hwloc(void) { |
| 1142 | /* No-op when hwloc is not used */ |
| 1143 | } |
| 1144 | |
| 1145 | #endif /* USE_HWLOC */ |
| 1146 | |
| 1147 | /* ============================================================================ |
| 1148 | * NUMA support |
| 1149 | * ============================================================================ */ |
| 1150 | |
| 1151 | static void init_numa_topology(void) { |
| 1152 | /* Initialize topology arrays */ |
| 1153 | memset(g_cpus_per_node, 0, sizeof(g_cpus_per_node)); |
| 1154 | memset(g_node_cpus, 0, sizeof(g_node_cpus)); |
| 1155 | |
| 1156 | #ifdef USE_NUMA |
| 1157 | if (numa_available() >= 0 && g_numa_nodes > 1) { |
| 1158 | /* Build CPU-to-node mapping using libnuma */ |
| 1159 | for (int cpu = 0; cpu < g_num_cpus && cpu < MAX_NUMA_NODES * MAX_CPUS_PER_NODE; cpu++) { |
| 1160 | int node = numa_node_of_cpu(cpu); |
| 1161 | if (node >= 0 && node < MAX_NUMA_NODES) { |
| 1162 | int idx = g_cpus_per_node[node]; |
| 1163 | if (idx < MAX_CPUS_PER_NODE) { |
| 1164 | g_node_cpus[node][idx] = cpu; |
| 1165 | g_cpus_per_node[node]++; |
| 1166 | } |
| 1167 | } |
| 1168 | } |
| 1169 | |
| 1170 | if (g_verbose) { |
| 1171 | fprintf(stderr, "NUMA topology:\n"); |
| 1172 | for (int node = 0; node < g_numa_nodes; node++) { |
| 1173 | fprintf(stderr, " Node %d: %d CPUs (first: %d, last: %d)\n", |
| 1174 | node, g_cpus_per_node[node], |
| 1175 | g_cpus_per_node[node] > 0 ? g_node_cpus[node][0] : -1, |
| 1176 | g_cpus_per_node[node] > 0 ? g_node_cpus[node][g_cpus_per_node[node]-1] : -1); |
| 1177 | } |
| 1178 | } |
| 1179 | } else |
| 1180 | #endif |
| 1181 | { |
| 1182 | /* UMA or NUMA not enabled: all CPUs on "node 0" */ |
| 1183 | for (int cpu = 0; cpu < g_num_cpus && cpu < MAX_CPUS_PER_NODE; cpu++) { |
| 1184 | g_node_cpus[0][cpu] = cpu; |
| 1185 | } |
| 1186 | g_cpus_per_node[0] = g_num_cpus < MAX_CPUS_PER_NODE ? g_num_cpus : MAX_CPUS_PER_NODE; |
| 1187 | } |
| 1188 | } |
| 1189 | |
| 1190 | static void init_numa(void) { |
| 1191 | #ifdef USE_NUMA |
| 1192 | if (numa_available() >= 0) { |
| 1193 | g_numa_nodes = numa_max_node() + 1; |
| 1194 | if (g_verbose) { |
| 1195 | fprintf(stderr, "NUMA: %d nodes detected (libnuma enabled)\n", g_numa_nodes); |
| 1196 | } |
| 1197 | } else { |
| 1198 | g_numa_nodes = 1; |
| 1199 | if (g_verbose) { |
| 1200 | fprintf(stderr, "NUMA: not available (libnuma enabled but no NUMA support)\n"); |
| 1201 | } |
| 1202 | } |
| 1203 | #else |
| 1204 | g_numa_nodes = 1; |
| 1205 | if (g_verbose) { |
| 1206 | fprintf(stderr, "NUMA: disabled (compile with -DUSE_NUMA -lnuma to enable)\n"); |
| 1207 | } |
| 1208 | #endif |
| 1209 | |
| 1210 | /* Build NUMA topology after detecting nodes */ |
| 1211 | init_numa_topology(); |
| 1212 | } |
| 1213 | |
| 1214 | |
| 1215 | /* ============================================================================ |
| 1216 | * System info |
| 1217 | * ============================================================================ */ |
| 1218 | |
| 1219 | static void init_system_info(void) { |
| 1220 | /* Get number of CPUs (POSIX, works on all platforms) */ |
| 1221 | g_num_cpus = sysconf(_SC_NPROCESSORS_ONLN); |
| 1222 | if (g_num_cpus < 1) g_num_cpus = 1; |
| 1223 | |
| 1224 | /* Get total memory (platform-specific methods) */ |
| 1225 | g_total_memory = 0; |
| 1226 | |
| 1227 | #ifdef PLATFORM_LINUX |
| 1228 | /* Linux: sysconf is reliable */ |
| 1229 | long pages = sysconf(_SC_PHYS_PAGES); |
| 1230 | long page_size = sysconf(_SC_PAGESIZE); |
| 1231 | if (pages > 0 && page_size > 0) { |
| 1232 | g_total_memory = (size_t)pages * (size_t)page_size; |
| 1233 | } |
| 1234 | #endif |
| 1235 | |
| 1236 | #ifdef PLATFORM_MACOS |
| 1237 | /* macOS: use sysctl hw.memsize */ |
| 1238 | int64_t memsize = 0; |
| 1239 | size_t len = sizeof(memsize); |
| 1240 | if (sysctlbyname("hw.memsize", &memsize, &len, NULL, 0) == 0 && memsize > 0) { |
| 1241 | g_total_memory = (size_t)memsize; |
| 1242 | } |
| 1243 | #endif |
| 1244 | |
| 1245 | #ifdef PLATFORM_BSD |
| 1246 | /* BSD: try hw.physmem or hw.realmem */ |
| 1247 | unsigned long physmem = 0; |
| 1248 | size_t len = sizeof(physmem); |
| 1249 | if (sysctlbyname("hw.physmem", &physmem, &len, NULL, 0) == 0 && physmem > 0) { |
| 1250 | g_total_memory = (size_t)physmem; |
| 1251 | } else { |
| 1252 | /* Fallback to sysconf */ |
| 1253 | long pages = sysconf(_SC_PHYS_PAGES); |
| 1254 | long page_size = sysconf(_SC_PAGESIZE); |
| 1255 | if (pages > 0 && page_size > 0) { |
| 1256 | g_total_memory = (size_t)pages * (size_t)page_size; |
| 1257 | } |
| 1258 | } |
| 1259 | #endif |
| 1260 | |
| 1261 | /* Fallback if detection failed */ |
| 1262 | if (g_total_memory == 0) { |
| 1263 | long pages = sysconf(_SC_PHYS_PAGES); |
| 1264 | long page_size = sysconf(_SC_PAGESIZE); |
| 1265 | if (pages > 0 && page_size > 0) { |
| 1266 | g_total_memory = (size_t)pages * (size_t)page_size; |
| 1267 | } else { |
| 1268 | g_total_memory = 1024UL * 1024 * 1024; /* Default 1GB */ |
| 1269 | } |
| 1270 | } |
| 1271 | |
| 1272 | if (g_verbose) { |
| 1273 | fprintf(stderr, "System: %d CPUs, %.2f GB memory\n", |
| 1274 | g_num_cpus, g_total_memory / (1024.0 * 1024 * 1024)); |
| 1275 | } |
| 1276 | |
| 1277 | /* Detect cache topology (must be called after g_num_cpus is set) */ |
| 1278 | init_cache_info(); |
| 1279 | } |
| 1280 | |
| 1281 | /* ============================================================================ |
| 1282 | * OpenMP Bandwidth Benchmark |
| 1283 | * ============================================================================ */ |
| 1284 | |
| 1285 | /* |
| 1286 | * Run bandwidth benchmark using OpenMP. |
| 1287 | * |
| 1288 | * Key features: |
| 1289 | * - proc_bind(spread) distributes threads across NUMA nodes |
| 1290 | * - Per-thread NUMA-local buffer allocation |
| 1291 | * - Implicit barrier synchronization (more efficient than pthread_barrier) |
| 1292 | * - 8-accumulator read for optimal bandwidth measurement |
| 1293 | */ |
| 1294 | static result_t run_benchmark_omp(size_t size, operation_t op, int nthreads) { |
| 1295 | result_t result = {0}; |
| 1296 | result.size = size; |
| 1297 | result.op = op; |
| 1298 | result.threads = nthreads; |
| 1299 | |
| 1300 | /* Allocate arrays for per-thread buffers and results */ |
| 1301 | void **src_bufs = calloc(nthreads, sizeof(void*)); |
| 1302 | void **dst_bufs = calloc(nthreads, sizeof(void*)); |
| 1303 | double *thread_elapsed = calloc(nthreads, sizeof(double)); |
| 1304 | uint64_t *thread_checksums = calloc(nthreads, sizeof(uint64_t)); |
| 1305 | int alloc_failed = 0; |
| 1306 | |
| 1307 | if (!src_bufs || !dst_bufs || !thread_elapsed || !thread_checksums) { |
| 1308 | free(src_bufs); |
| 1309 | free(dst_bufs); |
| 1310 | free(thread_elapsed); |
| 1311 | free(thread_checksums); |
| 1312 | return result; |
| 1313 | } |
| 1314 | |
| 1315 | /* Set OpenMP thread count */ |
| 1316 | omp_set_num_threads(nthreads); |
| 1317 | |
| 1318 | /* Phase 1: Parallel allocation with NUMA awareness |
| 1319 | * proc_bind(spread) distributes threads across NUMA nodes, |
| 1320 | * then each thread allocates memory locally */ |
| 1321 | #pragma omp parallel proc_bind(spread) |
| 1322 | { |
| 1323 | int tid = omp_get_thread_num(); |
| 1324 | |
| 1325 | #ifdef USE_NUMA |
| 1326 | /* Get current CPU and its NUMA node (OpenMP has placed us optimally) */ |
| 1327 | if (numa_available() >= 0) { |
| 1328 | int cpu = sched_getcpu(); |
| 1329 | int node = numa_node_of_cpu(cpu); |
| 1330 | if (node >= 0) { |
| 1331 | /* Allocate on local NUMA node */ |
| 1332 | src_bufs[tid] = numa_alloc_onnode(size, node); |
| 1333 | if (op == OP_COPY) { |
| 1334 | dst_bufs[tid] = numa_alloc_onnode(size, node); |
| 1335 | } |
| 1336 | } |
| 1337 | } |
| 1338 | #endif |
| 1339 | |
| 1340 | /* Fallback: regular allocation if NUMA not available or failed */ |
| 1341 | if (!src_bufs[tid]) { |
| 1342 | src_bufs[tid] = alloc_buffer(size); |
| 1343 | } |
| 1344 | if (op == OP_COPY && !dst_bufs[tid]) { |
| 1345 | dst_bufs[tid] = alloc_buffer(size); |
| 1346 | } |
| 1347 | |
| 1348 | /* Check allocation success */ |
| 1349 | if (!src_bufs[tid] || (op == OP_COPY && !dst_bufs[tid])) { |
| 1350 | #pragma omp atomic write |
| 1351 | alloc_failed = 1; |
| 1352 | } |
| 1353 | |
| 1354 | /* Initialize buffer (first-touch for NUMA) */ |
| 1355 | if (src_bufs[tid]) { |
| 1356 | memset(src_bufs[tid], 0xAA, size); |
| 1357 | } |
| 1358 | if (dst_bufs[tid]) { |
| 1359 | memset(dst_bufs[tid], 0, size); |
| 1360 | } |
| 1361 | } |
| 1362 | |
| 1363 | if (alloc_failed) { |
| 1364 | /* Cleanup on allocation failure */ |
| 1365 | for (int i = 0; i < nthreads; i++) { |
| 1366 | #ifdef USE_NUMA |
| 1367 | if (numa_available() >= 0) { |
| 1368 | if (src_bufs[i]) numa_free(src_bufs[i], size); |
| 1369 | if (dst_bufs[i]) numa_free(dst_bufs[i], size); |
| 1370 | } else |
| 1371 | #endif |
| 1372 | { |
| 1373 | free_buffer(src_bufs[i], size); |
| 1374 | free_buffer(dst_bufs[i], size); |
| 1375 | } |
| 1376 | } |
| 1377 | free(src_bufs); |
| 1378 | free(dst_bufs); |
| 1379 | free(thread_elapsed); |
| 1380 | free(thread_checksums); |
| 1381 | if (g_verbose) { |
| 1382 | fprintf(stderr, "Failed to allocate %zu bytes × %d threads\n", size, nthreads); |
| 1383 | } |
| 1384 | return result; |
| 1385 | } |
| 1386 | |
| 1387 | /* Phase 2: Calibration - estimate iterations needed */ |
| 1388 | int iterations = MIN_ITERATIONS; |
| 1389 | { |
| 1390 | /* Warmup */ |
| 1391 | g_sink += mem_read(src_bufs[0], size); |
| 1392 | |
| 1393 | /* Time single iteration */ |
| 1394 | double t_start = get_time(); |
| 1395 | switch (op) { |
| 1396 | case OP_READ: |
| 1397 | g_sink += mem_read(src_bufs[0], size); |
| 1398 | break; |
| 1399 | case OP_WRITE: |
| 1400 | mem_write(src_bufs[0], size, 0x1234567890ABCDEFULL); |
| 1401 | break; |
| 1402 | case OP_COPY: |
| 1403 | mem_copy(dst_bufs[0], src_bufs[0], size); |
| 1404 | break; |
| 1405 | default: |
| 1406 | break; |
| 1407 | } |
| 1408 | double time_per_iter = get_time() - t_start; |
| 1409 | |
| 1410 | if (time_per_iter > 1e-9) { |
| 1411 | iterations = (int)(TARGET_TIME_PER_TEST / time_per_iter); |
| 1412 | if (iterations < MIN_ITERATIONS) iterations = MIN_ITERATIONS; |
| 1413 | if (iterations > MAX_ITERATIONS) iterations = MAX_ITERATIONS; |
| 1414 | } |
| 1415 | } |
| 1416 | result.iterations = iterations; |
| 1417 | |
| 1418 | /* Phase 3: Timed measurement with all threads |
| 1419 | * OpenMP implicit barrier ensures all threads start together */ |
| 1420 | #pragma omp parallel proc_bind(spread) |
| 1421 | { |
| 1422 | int tid = omp_get_thread_num(); |
| 1423 | void *src = src_bufs[tid]; |
| 1424 | void *dst = dst_bufs[tid]; |
| 1425 | uint64_t checksum = 0; |
| 1426 | |
| 1427 | /* Implicit barrier here - all threads synchronized */ |
| 1428 | |
| 1429 | double t_start = get_time(); |
| 1430 | |
| 1431 | switch (op) { |
| 1432 | case OP_READ: |
| 1433 | for (int i = 0; i < iterations; i++) { |
| 1434 | checksum ^= mem_read(src, size); |
| 1435 | } |
| 1436 | break; |
| 1437 | case OP_WRITE: |
| 1438 | for (int i = 0; i < iterations; i++) { |
| 1439 | mem_write(src, size, (uint64_t)i); |
| 1440 | } |
| 1441 | break; |
| 1442 | case OP_COPY: |
| 1443 | for (int i = 0; i < iterations; i++) { |
| 1444 | mem_copy(dst, src, size); |
| 1445 | } |
| 1446 | break; |
| 1447 | default: |
| 1448 | break; |
| 1449 | } |
| 1450 | |
| 1451 | double t_end = get_time(); |
| 1452 | |
| 1453 | thread_elapsed[tid] = t_end - t_start; |
| 1454 | thread_checksums[tid] = checksum; |
| 1455 | } |
| 1456 | |
| 1457 | /* Find max elapsed time (determines overall bandwidth) */ |
| 1458 | double max_elapsed = 0; |
| 1459 | uint64_t total_checksum = 0; |
| 1460 | for (int i = 0; i < nthreads; i++) { |
| 1461 | if (thread_elapsed[i] > max_elapsed) { |
| 1462 | max_elapsed = thread_elapsed[i]; |
| 1463 | } |
| 1464 | total_checksum ^= thread_checksums[i]; |
| 1465 | } |
| 1466 | |
| 1467 | g_sink += total_checksum; |
| 1468 | result.elapsed_s = max_elapsed; |
| 1469 | |
| 1470 | /* Calculate bandwidth = (size per thread * threads * iterations) / time |
| 1471 | * This gives aggregate bandwidth across all threads. |
| 1472 | * Note: for copy, we report buffer size (not 2x) to match bw_mem convention */ |
| 1473 | if (max_elapsed > 0) { |
| 1474 | size_t bytes_transferred = (size_t)size * nthreads * iterations; |
| 1475 | result.bandwidth_mb_s = (bytes_transferred / (1024.0 * 1024.0)) / max_elapsed; |
| 1476 | } |
| 1477 | |
| 1478 | /* Cleanup */ |
| 1479 | for (int i = 0; i < nthreads; i++) { |
| 1480 | #ifdef USE_NUMA |
| 1481 | if (numa_available() >= 0) { |
| 1482 | if (src_bufs[i]) numa_free(src_bufs[i], size); |
| 1483 | if (dst_bufs[i]) numa_free(dst_bufs[i], size); |
| 1484 | } else |
| 1485 | #endif |
| 1486 | { |
| 1487 | free_buffer(src_bufs[i], size); |
| 1488 | free_buffer(dst_bufs[i], size); |
| 1489 | } |
| 1490 | } |
| 1491 | free(src_bufs); |
| 1492 | free(dst_bufs); |
| 1493 | free(thread_elapsed); |
| 1494 | free(thread_checksums); |
| 1495 | |
| 1496 | return result; |
| 1497 | } |
| 1498 | |
| 1499 | /* Run single-threaded benchmark (for small buffers or latency) */ |
| 1500 | static result_t run_benchmark_single(size_t size, operation_t op) { |
| 1501 | result_t result = {0}; |
| 1502 | result.size = size; |
| 1503 | result.op = op; |
| 1504 | result.threads = 1; |
| 1505 | |
| 1506 | void *src = alloc_buffer(size); |
| 1507 | void *dst = (op == OP_COPY) ? alloc_buffer(size) : NULL; |
| 1508 | |
| 1509 | if (!src || (op == OP_COPY && !dst)) { |
| 1510 | free_buffer(src, size); |
| 1511 | free_buffer(dst, size); |
| 1512 | return result; |
| 1513 | } |
| 1514 | |
| 1515 | memset(src, 0xAA, size); |
| 1516 | if (dst) memset(dst, 0, size); |
| 1517 | |
| 1518 | /* Warmup */ |
| 1519 | g_sink += mem_read(src, size); |
| 1520 | |
| 1521 | /* Calibrate */ |
| 1522 | double t_start = get_time(); |
| 1523 | switch (op) { |
| 1524 | case OP_READ: g_sink += mem_read(src, size); break; |
| 1525 | case OP_WRITE: mem_write(src, size, 0x1234567890ABCDEFULL); break; |
| 1526 | case OP_COPY: mem_copy(dst, src, size); break; |
| 1527 | default: break; |
| 1528 | } |
| 1529 | double time_per_iter = get_time() - t_start; |
| 1530 | |
| 1531 | int iterations = MIN_ITERATIONS; |
| 1532 | if (time_per_iter > 1e-9) { |
| 1533 | iterations = (int)(TARGET_TIME_PER_TEST / time_per_iter); |
| 1534 | if (iterations < MIN_ITERATIONS) iterations = MIN_ITERATIONS; |
| 1535 | if (iterations > MAX_ITERATIONS) iterations = MAX_ITERATIONS; |
| 1536 | } |
| 1537 | result.iterations = iterations; |
| 1538 | |
| 1539 | /* Timed run */ |
| 1540 | uint64_t checksum = 0; |
| 1541 | t_start = get_time(); |
| 1542 | |
| 1543 | switch (op) { |
| 1544 | case OP_READ: |
| 1545 | for (int i = 0; i < iterations; i++) { |
| 1546 | checksum ^= mem_read(src, size); |
| 1547 | } |
| 1548 | break; |
| 1549 | case OP_WRITE: |
| 1550 | for (int i = 0; i < iterations; i++) { |
| 1551 | mem_write(src, size, (uint64_t)i); |
| 1552 | } |
| 1553 | break; |
| 1554 | case OP_COPY: |
| 1555 | for (int i = 0; i < iterations; i++) { |
| 1556 | mem_copy(dst, src, size); |
| 1557 | } |
| 1558 | break; |
| 1559 | default: |
| 1560 | break; |
| 1561 | } |
| 1562 | |
| 1563 | double elapsed = get_time() - t_start; |
| 1564 | |
| 1565 | g_sink += checksum; |
| 1566 | result.elapsed_s = elapsed; |
| 1567 | |
| 1568 | if (elapsed > 0) { |
| 1569 | size_t bytes_transferred = size * iterations; |
| 1570 | result.bandwidth_mb_s = (bytes_transferred / (1024.0 * 1024.0)) / elapsed; |
| 1571 | } |
| 1572 | |
| 1573 | free_buffer(src, size); |
| 1574 | free_buffer(dst, size); |
| 1575 | |
| 1576 | return result; |
| 1577 | } |
| 1578 | |
| 1579 | /* Main benchmark runner - dispatches to OpenMP or single-threaded */ |
| 1580 | static result_t run_benchmark(size_t size, operation_t op, int nthreads) { |
| 1581 | if (nthreads == 1) { |
| 1582 | return run_benchmark_single(size, op); |
| 1583 | } |
| 1584 | return run_benchmark_omp(size, op, nthreads); |
| 1585 | } |
| 1586 | |
| 1587 | /* Run benchmark multiple times and return best result (like lmbench TRIES) |
| 1588 | * For bandwidth: best = highest bandwidth |
| 1589 | * For latency: best = lowest latency |
| 1590 | * |
| 1591 | * First run is a warmup (discarded) to allow CPU frequency to ramp up |
| 1592 | * and caches to warm. This dramatically reduces result variability. |
| 1593 | */ |
| 1594 | static result_t run_benchmark_best(size_t size, operation_t op, int nthreads) { |
| 1595 | result_t best = {0}; |
| 1596 | |
| 1597 | /* Warmup run - discarded. |
| 1598 | * This allows: CPU to reach turbo frequency, caches to warm, |
| 1599 | * thread scheduling to stabilize. Critical for consistent results. */ |
| 1600 | (void)run_benchmark(size, op, nthreads); |
| 1601 | |
| 1602 | for (int try = 0; try < g_benchmark_tries; try++) { |
| 1603 | result_t r = run_benchmark(size, op, nthreads); |
| 1604 | |
| 1605 | if (try == 0) { |
| 1606 | best = r; |
| 1607 | } else { |
| 1608 | if (op == OP_LATENCY) { |
| 1609 | /* For latency: lower is better */ |
| 1610 | if (r.latency_ns > 0 && r.latency_ns < best.latency_ns) { |
| 1611 | best = r; |
| 1612 | } |
| 1613 | } else { |
| 1614 | /* For bandwidth: higher is better */ |
| 1615 | if (r.bandwidth_mb_s > best.bandwidth_mb_s) { |
| 1616 | best = r; |
| 1617 | } |
| 1618 | } |
| 1619 | } |
| 1620 | } |
| 1621 | |
| 1622 | return best; |
| 1623 | } |
| 1624 | |
| 1625 | /* ============================================================================ |
| 1626 | * Main benchmark loop |
| 1627 | * ============================================================================ */ |
| 1628 | |
| 1629 | /* Generate thread counts dynamically based on CPU count (for auto-scaling mode) |
| 1630 | * |
| 1631 | * Strategy: |
| 1632 | * - Powers of 2 from 1 up to nproc |
| 1633 | * - Always include nproc itself (if not already a power of 2) |
| 1634 | * - No oversubscription (causes unreliable results) |
| 1635 | * |
| 1636 | * Examples: |
| 1637 | * 4 cores: 1, 2, 4 (3 values) |
| 1638 | * 32 cores: 1, 2, 4, 8, 16, 32 (6 values) |
| 1639 | * 48 cores: 1, 2, 4, 8, 16, 32, 48 (7 values) |
| 1640 | */ |
| 1641 | static int* get_thread_counts(int *count) { |
| 1642 | int nproc = g_num_cpus; |
| 1643 | if (nproc < 1) nproc = 1; |
| 1644 | |
| 1645 | /* Cap at nproc - oversubscription causes unreliable benchmark results |
| 1646 | * due to context switching, cache thrashing, and scheduler interference */ |
| 1647 | int max_threads = nproc; |
| 1648 | |
| 1649 | /* Allocate more than enough space */ |
| 1650 | int *tc = malloc(32 * sizeof(int)); |
| 1651 | int n = 0; |
| 1652 | |
| 1653 | /* Add powers of 2 up to nproc */ |
| 1654 | for (int t = 1; t <= max_threads; t *= 2) { |
| 1655 | tc[n++] = t; |
| 1656 | } |
| 1657 | |
| 1658 | /* Add nproc if not already in list (i.e., not a power of 2) */ |
| 1659 | if (tc[n-1] != nproc) { |
| 1660 | tc[n++] = nproc; |
| 1661 | } |
| 1662 | |
| 1663 | tc[n] = 0; /* Sentinel */ |
| 1664 | *count = n; |
| 1665 | return tc; |
| 1666 | } |
| 1667 | |
| 1668 | /* Round size to nearest power of 2 for cleaner output */ |
| 1669 | static size_t round_to_power_of_2(size_t size) { |
| 1670 | if (size == 0) return 4096; |
| 1671 | size_t power = 1; |
| 1672 | while (power < size) power <<= 1; |
| 1673 | /* Return closer of power and power/2 */ |
| 1674 | if (power - size > size - power/2 && power/2 >= 4096) { |
| 1675 | return power / 2; |
| 1676 | } |
| 1677 | return power; |
| 1678 | } |
| 1679 | |
| 1680 | /* Get sizes to test (per-thread buffer sizes) - adaptive based on cache hierarchy |
| 1681 | * |
| 1682 | * Generates sizes at critical cache transition points to show: |
| 1683 | * 1. Pure L1 performance |
| 1684 | * 2. L1→L2 transition |
| 1685 | * 3. Pure L2 performance |
| 1686 | * 4. L2→L3 transition |
| 1687 | * 5. L3 region |
| 1688 | * 6. Pure RAM bandwidth |
| 1689 | * |
| 1690 | * All sizes are strictly increasing with no overlaps. |
| 1691 | */ |
| 1692 | static size_t* get_sizes(int *count) { |
| 1693 | int nthreads = g_explicit_threads > 0 ? g_explicit_threads : g_num_cpus; |
| 1694 | if (nthreads < 1) nthreads = 1; |
| 1695 | |
| 1696 | /* Use detected cache sizes, with sensible defaults */ |
| 1697 | size_t l1 = g_l1_cache_size > 0 ? g_l1_cache_size : 32768; /* 32 KB */ |
| 1698 | size_t l2 = g_l2_cache_size > 0 ? g_l2_cache_size : 262144; /* 256 KB */ |
| 1699 | size_t l3 = g_l3_cache_size > 0 ? g_l3_cache_size : 8388608; /* 8 MB */ |
| 1700 | |
| 1701 | /* Memory limit per thread */ |
| 1702 | size_t max_size = g_total_memory / 2 / nthreads; |
| 1703 | |
| 1704 | /* Build strictly increasing size sequence */ |
| 1705 | size_t sizes_list[20]; |
| 1706 | int n = 0; |
| 1707 | size_t prev = 0; |
| 1708 | |
| 1709 | /* Helper macro to add size if > prev and <= max_size */ |
| 1710 | #define ADD_SIZE(sz) do { \ |
| 1711 | size_t _s = round_to_power_of_2(sz); \ |
| 1712 | if (_s > prev && _s <= max_size) { sizes_list[n++] = _s; prev = _s; } \ |
| 1713 | } while(0) |
| 1714 | |
| 1715 | /* L1 region */ |
| 1716 | ADD_SIZE(l1 / 2); |
| 1717 | |
| 1718 | /* L1→L2 transition */ |
| 1719 | ADD_SIZE(l1 * 2); |
| 1720 | |
| 1721 | /* L2 region */ |
| 1722 | ADD_SIZE(l2 / 2); |
| 1723 | ADD_SIZE(l2); |
| 1724 | |
| 1725 | /* L2→L3 transition */ |
| 1726 | ADD_SIZE(l2 * 2); |
| 1727 | |
| 1728 | /* L3 region */ |
| 1729 | if (l3 > l2 * 4) { |
| 1730 | ADD_SIZE(l3 / 4); |
| 1731 | } |
| 1732 | ADD_SIZE(l3 / 2); |
| 1733 | |
| 1734 | /* L3→RAM transition */ |
| 1735 | ADD_SIZE(l3); |
| 1736 | |
| 1737 | /* RAM region */ |
| 1738 | ADD_SIZE(l3 * 2); |
| 1739 | ADD_SIZE(l3 * 4); |
| 1740 | |
| 1741 | /* Full sweep: add larger sizes up to memory limit */ |
| 1742 | if (g_full_sweep) { |
| 1743 | size_t ram_size = RAM_SIZE_2 * 2; |
| 1744 | while (ram_size <= max_size && n < 18) { |
| 1745 | ADD_SIZE(ram_size); |
| 1746 | ram_size *= 2; |
| 1747 | } |
| 1748 | } |
| 1749 | |
| 1750 | #undef ADD_SIZE |
| 1751 | |
| 1752 | /* Ensure at least one size */ |
| 1753 | if (n == 0) { |
| 1754 | sizes_list[n++] = 4096; |
| 1755 | } |
| 1756 | |
| 1757 | /* Copy to result array */ |
| 1758 | size_t *sizes = malloc((n + 1) * sizeof(size_t)); |
| 1759 | for (int i = 0; i < n; i++) { |
| 1760 | sizes[i] = sizes_list[i]; |
| 1761 | } |
| 1762 | sizes[n] = 0; |
| 1763 | *count = n; |
| 1764 | return sizes; |
| 1765 | } |
| 1766 | |
| 1767 | /* Format size for human readable output (e.g., 1024 KB -> "1 MB") */ |
| 1768 | static const char* format_size(size_t size_kb, char *buf, size_t buf_size) { |
| 1769 | if (size_kb >= 1024 * 1024) { |
| 1770 | snprintf(buf, buf_size, "%zu GB", size_kb / (1024 * 1024)); |
| 1771 | } else if (size_kb >= 1024) { |
| 1772 | snprintf(buf, buf_size, "%zu MB", size_kb / 1024); |
| 1773 | } else { |
| 1774 | snprintf(buf, buf_size, "%zu KB", size_kb); |
| 1775 | } |
| 1776 | return buf; |
| 1777 | } |
| 1778 | |
| 1779 | /* Format bandwidth for human readable output */ |
| 1780 | static const char* format_bandwidth(double mb_s, char *buf, size_t buf_size) { |
| 1781 | if (mb_s >= 1000000) { |
| 1782 | snprintf(buf, buf_size, "%.1f TB/s", mb_s / 1000000); |
| 1783 | } else if (mb_s >= 1000) { |
| 1784 | snprintf(buf, buf_size, "%.1f GB/s", mb_s / 1000); |
| 1785 | } else { |
| 1786 | snprintf(buf, buf_size, "%.1f MB/s", mb_s); |
| 1787 | } |
| 1788 | return buf; |
| 1789 | } |
| 1790 | |
| 1791 | static void print_csv_header(void) { |
| 1792 | if (g_human_readable) { |
| 1793 | printf("\n%-10s %-8s %12s %12s %8s\n", |
| 1794 | "Size", "Op", "Bandwidth", "Latency", "Threads"); |
| 1795 | printf("%-10s %-8s %12s %12s %8s\n", |
| 1796 | "----", "--", "---------", "-------", "-------"); |
| 1797 | } else { |
| 1798 | printf("size_kb,operation,bandwidth_mb_s,latency_ns,latency_stddev_ns,latency_samples,threads,iterations,elapsed_s\n"); |
| 1799 | } |
| 1800 | } |
| 1801 | |
| 1802 | static void print_result(const result_t *r) { |
| 1803 | size_t size_kb = r->size / 1024; |
| 1804 | |
| 1805 | if (g_human_readable) { |
| 1806 | char size_buf[32], bw_buf[32]; |
| 1807 | format_size(size_kb, size_buf, sizeof(size_buf)); |
| 1808 | |
| 1809 | if (r->op == OP_LATENCY) { |
| 1810 | printf("%-10s %-8s %12s %9.1f ns %8d\n", |
| 1811 | size_buf, OP_NAMES[r->op], "-", r->latency_ns, r->threads); |
| 1812 | } else { |
| 1813 | format_bandwidth(r->bandwidth_mb_s, bw_buf, sizeof(bw_buf)); |
| 1814 | printf("%-10s %-8s %12s %12s %8d\n", |
| 1815 | size_buf, OP_NAMES[r->op], bw_buf, "-", r->threads); |
| 1816 | } |
| 1817 | } else { |
| 1818 | if (r->op == OP_LATENCY) { |
| 1819 | /* For latency test: report median, stddev, and sample count for statistical validity |
| 1820 | * Median is robust to outliers and provides reliable central tendency |
| 1821 | * StdDev indicates measurement precision |
| 1822 | * Sample count shows measurement effort */ |
| 1823 | printf("%zu,%s,0,%.2f,%.2f,%d,%d,%d,%.6f\n", |
| 1824 | size_kb, OP_NAMES[r->op], r->latency_ns, |
| 1825 | r->latency_stddev_ns, r->latency_samples, |
| 1826 | r->threads, r->iterations, r->elapsed_s); |
| 1827 | } else { |
| 1828 | /* For bandwidth tests, latency fields are 0 */ |
| 1829 | printf("%zu,%s,%.2f,0,0,0,%d,%d,%.6f\n", |
| 1830 | size_kb, OP_NAMES[r->op], r->bandwidth_mb_s, |
| 1831 | r->threads, r->iterations, r->elapsed_s); |
| 1832 | } |
| 1833 | } |
| 1834 | } |
| 1835 | |
| 1836 | /* Update summary statistics with a new result */ |
| 1837 | static void update_summary(const result_t *r) { |
| 1838 | /* Weight by log2 of size - larger sizes get more weight */ |
| 1839 | double weight = log2((double)r->size / 1024.0 + 1.0); |
| 1840 | |
| 1841 | /* Track largest size tested */ |
| 1842 | if (r->size > g_summary.largest_size_tested) { |
| 1843 | g_summary.largest_size_tested = r->size; |
| 1844 | } |
| 1845 | |
| 1846 | switch (r->op) { |
| 1847 | case OP_READ: |
| 1848 | g_summary.read_count++; |
| 1849 | if (r->bandwidth_mb_s > g_summary.peak_read_mb_s) { |
| 1850 | g_summary.peak_read_mb_s = r->bandwidth_mb_s; |
| 1851 | } |
| 1852 | g_summary.read_bw_weighted_sum += r->bandwidth_mb_s * weight; |
| 1853 | g_summary.read_weight_sum += weight; |
| 1854 | break; |
| 1855 | |
| 1856 | case OP_WRITE: |
| 1857 | g_summary.write_count++; |
| 1858 | if (r->bandwidth_mb_s > g_summary.peak_write_mb_s) { |
| 1859 | g_summary.peak_write_mb_s = r->bandwidth_mb_s; |
| 1860 | } |
| 1861 | g_summary.write_bw_weighted_sum += r->bandwidth_mb_s * weight; |
| 1862 | g_summary.write_weight_sum += weight; |
| 1863 | break; |
| 1864 | |
| 1865 | case OP_COPY: |
| 1866 | g_summary.copy_count++; |
| 1867 | if (r->bandwidth_mb_s > g_summary.peak_copy_mb_s) { |
| 1868 | g_summary.peak_copy_mb_s = r->bandwidth_mb_s; |
| 1869 | } |
| 1870 | g_summary.copy_bw_weighted_sum += r->bandwidth_mb_s * weight; |
| 1871 | g_summary.copy_weight_sum += weight; |
| 1872 | break; |
| 1873 | |
| 1874 | case OP_LATENCY: |
| 1875 | g_summary.latency_count++; |
| 1876 | /* For latency, track the largest buffer size tested for the most RAM-like result */ |
| 1877 | if (r->latency_ns > 0 && r->size >= g_summary.largest_size_tested) { |
| 1878 | /* Always update with the largest size measurement */ |
| 1879 | g_summary.best_latency_ns = r->latency_ns; |
| 1880 | } |
| 1881 | break; |
| 1882 | } |
| 1883 | } |
| 1884 | |
| 1885 | /* Print summary statistics */ |
| 1886 | static void print_summary(void) { |
| 1887 | fprintf(stderr, "\n"); |
| 1888 | fprintf(stderr, "================================================================================\n"); |
| 1889 | fprintf(stderr, " BENCHMARK SUMMARY\n"); |
| 1890 | fprintf(stderr, "================================================================================\n\n"); |
| 1891 | |
| 1892 | /* Calculate weighted averages */ |
| 1893 | if (g_summary.read_weight_sum > 0) { |
| 1894 | g_summary.weighted_avg_read_mb_s = g_summary.read_bw_weighted_sum / g_summary.read_weight_sum; |
| 1895 | } |
| 1896 | if (g_summary.write_weight_sum > 0) { |
| 1897 | g_summary.weighted_avg_write_mb_s = g_summary.write_bw_weighted_sum / g_summary.write_weight_sum; |
| 1898 | } |
| 1899 | if (g_summary.copy_weight_sum > 0) { |
| 1900 | g_summary.weighted_avg_copy_mb_s = g_summary.copy_bw_weighted_sum / g_summary.copy_weight_sum; |
| 1901 | } |
| 1902 | |
| 1903 | /* Print bandwidth results */ |
| 1904 | fprintf(stderr, "BANDWIDTH (MB/s):\n"); |
| 1905 | fprintf(stderr, " %-10s %12s %12s\n", "Operation", "Peak", "Weighted Avg"); |
| 1906 | fprintf(stderr, " %-10s %12s %12s\n", "---------", "----", "------------"); |
| 1907 | |
| 1908 | if (g_summary.read_count > 0) { |
| 1909 | fprintf(stderr, " %-10s %12.0f %12.0f\n", "Read", |
| 1910 | g_summary.peak_read_mb_s, g_summary.weighted_avg_read_mb_s); |
| 1911 | } |
| 1912 | if (g_summary.write_count > 0) { |
| 1913 | fprintf(stderr, " %-10s %12.0f %12.0f\n", "Write", |
| 1914 | g_summary.peak_write_mb_s, g_summary.weighted_avg_write_mb_s); |
| 1915 | } |
| 1916 | if (g_summary.copy_count > 0) { |
| 1917 | fprintf(stderr, " %-10s %12.0f %12.0f\n", "Copy", |
| 1918 | g_summary.peak_copy_mb_s, g_summary.weighted_avg_copy_mb_s); |
| 1919 | } |
| 1920 | |
| 1921 | /* Print latency results */ |
| 1922 | if (g_summary.latency_count > 0 && g_summary.best_latency_ns > 0) { |
| 1923 | fprintf(stderr, "\nLATENCY:\n"); |
| 1924 | const char *cache_note = ""; |
| 1925 | if (g_summary.largest_size_tested < 1024 * 1024) { |
| 1926 | cache_note = " (L2/L3 cache)"; |
| 1927 | } else if (g_summary.largest_size_tested < 64 * 1024 * 1024) { |
| 1928 | cache_note = " (L3 cache/RAM)"; |
| 1929 | } else { |
| 1930 | cache_note = " (RAM)"; |
| 1931 | } |
| 1932 | fprintf(stderr, " Best latency: %.1f ns%s at %zu KB buffer\n", |
| 1933 | g_summary.best_latency_ns, cache_note, g_summary.largest_size_tested / 1024); |
| 1934 | } |
| 1935 | |
| 1936 | /* Calculate and print composite benchmark score |
| 1937 | * Score formula: geometric mean of bandwidth scores, divided by latency factor |
| 1938 | * Higher is better for all components */ |
| 1939 | fprintf(stderr, "\n"); |
| 1940 | fprintf(stderr, "--------------------------------------------------------------------------------\n"); |
| 1941 | fprintf(stderr, "BENCHMARK SCORE (higher is better):\n\n"); |
| 1942 | |
| 1943 | /* Individual scores */ |
| 1944 | double bw_total = 0; |
| 1945 | int bw_count = 0; |
| 1946 | |
| 1947 | if (g_summary.peak_read_mb_s > 0) { |
| 1948 | bw_total += g_summary.peak_read_mb_s; |
| 1949 | bw_count++; |
| 1950 | } |
| 1951 | if (g_summary.peak_write_mb_s > 0) { |
| 1952 | bw_total += g_summary.peak_write_mb_s; |
| 1953 | bw_count++; |
| 1954 | } |
| 1955 | if (g_summary.peak_copy_mb_s > 0) { |
| 1956 | bw_total += g_summary.peak_copy_mb_s; |
| 1957 | bw_count++; |
| 1958 | } |
| 1959 | |
| 1960 | /* Bandwidth score: average of peak bandwidths (in GB/s for nicer numbers) */ |
| 1961 | double bw_score = 0; |
| 1962 | if (bw_count > 0) { |
| 1963 | bw_score = (bw_total / bw_count) / 1000.0; /* Convert MB/s to GB/s */ |
| 1964 | fprintf(stderr, " Bandwidth Score: %8.1f (avg peak bandwidth in GB/s)\n", bw_score); |
| 1965 | } |
| 1966 | |
| 1967 | /* Latency score: inverse of latency (higher = faster memory) */ |
| 1968 | double latency_score = 0; |
| 1969 | if (g_summary.best_latency_ns > 0) { |
| 1970 | latency_score = 1000.0 / g_summary.best_latency_ns; /* 1000/ns gives reasonable scale */ |
| 1971 | fprintf(stderr, " Latency Score: %8.1f (1000 / latency_ns)\n", latency_score); |
| 1972 | } |
| 1973 | |
| 1974 | /* Combined score: geometric mean if both available, otherwise just bandwidth */ |
| 1975 | double combined_score = 0; |
| 1976 | if (bw_score > 0 && latency_score > 0) { |
| 1977 | combined_score = sqrt(bw_score * latency_score) * 100; /* Scale for nice numbers */ |
| 1978 | fprintf(stderr, "\n >> COMBINED SCORE: %8.0f (sqrt(bw_score × latency_score) × 100)\n", combined_score); |
| 1979 | } else if (bw_score > 0) { |
| 1980 | combined_score = bw_score * 100; |
| 1981 | fprintf(stderr, "\n >> COMBINED SCORE: %8.0f (bandwidth only, no latency data)\n", combined_score); |
| 1982 | } |
| 1983 | |
| 1984 | fprintf(stderr, "--------------------------------------------------------------------------------\n"); |
| 1985 | |
| 1986 | /* Warn if options that affect score comparability were used */ |
| 1987 | int has_warnings = 0; |
| 1988 | if (g_max_runtime > 0 || g_explicit_threads > 0 || g_single_size > 0) { |
| 1989 | fprintf(stderr, "\n"); |
| 1990 | fprintf(stderr, "WARNING: Scores may not be comparable due to non-default options:\n"); |
| 1991 | if (g_max_runtime > 0) { |
| 1992 | fprintf(stderr, " - Time limit (-t %.0f) may have prevented testing larger buffer sizes\n", g_max_runtime); |
| 1993 | has_warnings = 1; |
| 1994 | } |
| 1995 | if (g_explicit_threads > 0) { |
| 1996 | fprintf(stderr, " - Fixed thread count (-p %d) instead of using all CPUs (%d)\n", |
| 1997 | g_explicit_threads, g_num_cpus); |
| 1998 | has_warnings = 1; |
| 1999 | } |
| 2000 | if (g_single_size > 0) { |
| 2001 | fprintf(stderr, " - Single buffer size (-s %zu KB) instead of full sweep\n", |
| 2002 | g_single_size / 1024); |
| 2003 | has_warnings = 1; |
| 2004 | } |
| 2005 | if (has_warnings) { |
| 2006 | fprintf(stderr, "For comparable scores, run without -t, -p, or -s options.\n"); |
| 2007 | } |
| 2008 | } |
| 2009 | fprintf(stderr, "\n"); |
| 2010 | } |
| 2011 | |
| 2012 | /* Maximum buffer size for latency test. |
| 2013 | * Must exceed largest L3 caches to measure true DRAM latency. |
| 2014 | * AMD EPYC 9754 (Genoa-X) has 1.1GB L3 cache, so we need > 1.1GB. |
| 2015 | * 2GB should cover any current processor. */ |
| 2016 | #define MAX_LATENCY_SIZE (2UL * 1024 * 1024 * 1024) /* 2 GB */ |
| 2017 | |
| 2018 | /* Find best configuration for a given buffer size and operation. |
| 2019 | * |
| 2020 | * This follows bw_mem's approach: |
| 2021 | * - buffer_size is the per-thread buffer size |
| 2022 | * - Total memory = buffer_size * threads (or buffer_size * threads * 2 for copy) |
| 2023 | * |
| 2024 | * Three modes: |
| 2025 | * 1. Auto-scaling (g_auto_scaling=1): Try multiple thread counts, find best |
| 2026 | * 2. Explicit threads (g_explicit_threads>0): Use exactly that many threads |
| 2027 | * 3. Default (neither): Use num_cpus threads |
| 2028 | */ |
| 2029 | static result_t find_best_config(size_t buffer_size, operation_t op, |
| 2030 | int *thread_counts, int tc_count) { |
| 2031 | result_t best = {0}; |
| 2032 | best.size = buffer_size; |
| 2033 | best.op = op; |
| 2034 | |
| 2035 | /* For latency test: single-thread, statistically valid measurement */ |
| 2036 | if (op == OP_LATENCY) { |
| 2037 | size_t max_latency = MAX_LATENCY_SIZE; |
| 2038 | if (g_total_memory / 4 < max_latency) { |
| 2039 | max_latency = g_total_memory / 4; |
| 2040 | } |
| 2041 | size_t latency_size = (buffer_size > max_latency) ? max_latency : buffer_size; |
| 2042 | |
| 2043 | double start = get_time(); |
| 2044 | latency_stats_t stats = measure_latency_stats(latency_size); |
| 2045 | double elapsed = get_time() - start; |
| 2046 | |
| 2047 | best.size = buffer_size; |
| 2048 | best.op = op; |
| 2049 | best.threads = 1; |
| 2050 | best.latency_ns = stats.median_ns; |
| 2051 | best.latency_mean_ns = stats.mean_ns; |
| 2052 | best.latency_stddev_ns = stats.stddev_ns; |
| 2053 | best.latency_cv = stats.cv; |
| 2054 | best.latency_samples = stats.num_samples; |
| 2055 | best.elapsed_s = elapsed; |
| 2056 | best.iterations = stats.num_samples; |
| 2057 | |
| 2058 | return best; |
| 2059 | } |
| 2060 | |
| 2061 | /* Bandwidth tests */ |
| 2062 | int nthreads; |
| 2063 | |
| 2064 | if (g_auto_scaling) { |
| 2065 | /* Auto-scaling mode: try all thread counts, find best */ |
| 2066 | for (int i = 0; i < tc_count; i++) { |
| 2067 | nthreads = thread_counts[i]; |
| 2068 | if (nthreads < 1) continue; |
| 2069 | |
| 2070 | int bufs_per_op = (op == OP_COPY) ? 2 : 1; |
| 2071 | size_t memory_needed = buffer_size * nthreads * bufs_per_op; |
| 2072 | if (memory_needed > g_total_memory / 4) { |
| 2073 | continue; |
| 2074 | } |
| 2075 | |
| 2076 | result_t r = run_benchmark_best(buffer_size, op, nthreads); |
| 2077 | r.size = buffer_size; |
| 2078 | |
| 2079 | if (r.bandwidth_mb_s > best.bandwidth_mb_s) { |
| 2080 | best = r; |
| 2081 | } |
| 2082 | } |
| 2083 | |
| 2084 | if (best.bandwidth_mb_s == 0) { |
| 2085 | best = run_benchmark_best(buffer_size, op, 1); |
| 2086 | best.size = buffer_size; |
| 2087 | } |
| 2088 | |
| 2089 | return best; |
| 2090 | } |
| 2091 | |
| 2092 | /* Fixed thread count mode */ |
| 2093 | if (g_explicit_threads > 0) { |
| 2094 | nthreads = g_explicit_threads; |
| 2095 | } else { |
| 2096 | nthreads = g_num_cpus; |
| 2097 | } |
| 2098 | |
| 2099 | /* Check memory limit and reduce threads if needed */ |
| 2100 | int bufs_per_op = (op == OP_COPY) ? 2 : 1; |
| 2101 | size_t memory_needed = buffer_size * nthreads * bufs_per_op; |
| 2102 | while (nthreads > 1 && memory_needed > g_total_memory / 4) { |
| 2103 | nthreads /= 2; |
| 2104 | memory_needed = buffer_size * nthreads * bufs_per_op; |
| 2105 | } |
| 2106 | |
| 2107 | best = run_benchmark_best(buffer_size, op, nthreads); |
| 2108 | best.size = buffer_size; |
| 2109 | |
| 2110 | return best; |
| 2111 | } |
| 2112 | |
| 2113 | static void run_all_benchmarks(void) { |
| 2114 | double start_time = get_time(); |
| 2115 | |
| 2116 | int tc_count; |
| 2117 | int *thread_counts = get_thread_counts(&tc_count); |
| 2118 | |
| 2119 | /* Single size mode */ |
| 2120 | if (g_single_size > 0) { |
| 2121 | if (g_verbose) { |
| 2122 | fprintf(stderr, "Testing buffer size: %zu KB per thread\n", |
| 2123 | g_single_size / 1024); |
| 2124 | } |
| 2125 | |
| 2126 | print_csv_header(); |
| 2127 | |
| 2128 | for (int op = 0; op < 4 && g_running; op++) { |
| 2129 | if (!(g_ops_mask & (1 << op))) continue; |
| 2130 | |
| 2131 | result_t best = find_best_config(g_single_size, (operation_t)op, |
| 2132 | thread_counts, tc_count); |
| 2133 | |
| 2134 | if (best.bandwidth_mb_s > 0 || best.latency_ns > 0) { |
| 2135 | print_result(&best); |
| 2136 | if (g_human_readable) update_summary(&best); |
| 2137 | fflush(stdout); |
| 2138 | } |
| 2139 | } |
| 2140 | |
| 2141 | free(thread_counts); |
| 2142 | |
| 2143 | if (g_verbose) { |
| 2144 | double total = get_time() - start_time; |
| 2145 | fprintf(stderr, "Total runtime: %.1f seconds\n", total); |
| 2146 | } |
| 2147 | |
| 2148 | /* Print summary in human-readable mode */ |
| 2149 | if (g_human_readable) print_summary(); |
| 2150 | return; |
| 2151 | } |
| 2152 | |
| 2153 | /* Normal mode: test all sizes */ |
| 2154 | int size_count; |
| 2155 | size_t *sizes = get_sizes(&size_count); |
| 2156 | |
| 2157 | if (g_verbose) { |
| 2158 | fprintf(stderr, "Testing %d buffer sizes (per thread, adaptive to cache hierarchy)\n", size_count); |
| 2159 | if (g_auto_scaling) { |
| 2160 | fprintf(stderr, "Thread mode: auto-scaling (trying 1-%d threads)\n", g_num_cpus); |
| 2161 | } else if (g_explicit_threads > 0) { |
| 2162 | fprintf(stderr, "Thread mode: fixed %d threads\n", g_explicit_threads); |
| 2163 | } else { |
| 2164 | fprintf(stderr, "Thread mode: num_cpus (%d threads)\n", g_num_cpus); |
| 2165 | } |
| 2166 | fprintf(stderr, "OpenMP: proc_bind(spread) for NUMA-aware thread placement\n"); |
| 2167 | } |
| 2168 | |
| 2169 | print_csv_header(); |
| 2170 | |
| 2171 | for (int s = 0; s < size_count && g_running; s++) { |
| 2172 | size_t size = sizes[s]; |
| 2173 | |
| 2174 | for (int op = 0; op < 4 && g_running; op++) { |
| 2175 | if (!(g_ops_mask & (1 << op))) continue; |
| 2176 | |
| 2177 | result_t best = find_best_config(size, (operation_t)op, |
| 2178 | thread_counts, tc_count); |
| 2179 | |
| 2180 | if (best.bandwidth_mb_s > 0 || best.latency_ns > 0) { |
| 2181 | print_result(&best); |
| 2182 | if (g_human_readable) update_summary(&best); |
| 2183 | fflush(stdout); |
| 2184 | } |
| 2185 | |
| 2186 | if (g_max_runtime > 0) { |
| 2187 | double elapsed = get_time() - start_time; |
| 2188 | if (elapsed > g_max_runtime) { |
| 2189 | if (g_verbose) { |
| 2190 | fprintf(stderr, "Time limit reached (%.1f s)\n", elapsed); |
| 2191 | } |
| 2192 | g_running = 0; |
| 2193 | break; |
| 2194 | } |
| 2195 | } |
| 2196 | } |
| 2197 | } |
| 2198 | |
| 2199 | free(sizes); |
| 2200 | free(thread_counts); |
| 2201 | |
| 2202 | if (g_verbose) { |
| 2203 | double total = get_time() - start_time; |
| 2204 | fprintf(stderr, "Total runtime: %.1f seconds\n", total); |
| 2205 | } |
| 2206 | |
| 2207 | /* Print summary in human-readable mode */ |
| 2208 | if (g_human_readable) print_summary(); |
| 2209 | } |
| 2210 | |
| 2211 | /* ============================================================================ |
| 2212 | * Main |
| 2213 | * ============================================================================ */ |
| 2214 | |
| 2215 | static void usage(const char *prog) { |
| 2216 | fprintf(stderr, "sc-membench %s - Memory Bandwidth Benchmark (OpenMP)\n\n", VERSION); |
| 2217 | fprintf(stderr, "Usage: %s [options]\n\n", prog); |
| 2218 | fprintf(stderr, "Options:\n"); |
| 2219 | fprintf(stderr, " -h Show this help\n"); |
| 2220 | fprintf(stderr, " -V Print version and exit\n"); |
| 2221 | fprintf(stderr, " -v Verbose output (use -vv for more detail)\n"); |
| 2222 | fprintf(stderr, " -s SIZE_KB Test only this buffer size (in KB), e.g. -s 1024 for 1MB\n"); |
| 2223 | fprintf(stderr, " -f Full sweep (test all sizes up to memory limit)\n"); |
| 2224 | fprintf(stderr, " Default: test up to 512 MB per thread\n"); |
| 2225 | fprintf(stderr, " -p THREADS Use exactly this many threads (default: num_cpus)\n"); |
| 2226 | fprintf(stderr, " -a Auto-scaling: try different thread counts to find best\n"); |
| 2227 | fprintf(stderr, " (slower but finds optimal thread count per buffer size)\n"); |
| 2228 | fprintf(stderr, " -t SECONDS Maximum runtime, 0 = unlimited (default: unlimited)\n"); |
| 2229 | fprintf(stderr, " -r TRIES Repeat each test N times, report best (default: %d)\n", DEFAULT_BENCHMARK_TRIES); |
| 2230 | fprintf(stderr, " -o OP Run only this operation: read, write, copy, or latency\n"); |
| 2231 | fprintf(stderr, " Can be specified multiple times (default: all)\n"); |
| 2232 | fprintf(stderr, " -H Enable huge pages for large buffers (>= 4MB)\n"); |
| 2233 | fprintf(stderr, " Uses THP (no setup needed) or explicit 2MB pages\n"); |
| 2234 | fprintf(stderr, " Automatically skipped for small buffers\n"); |
| 2235 | fprintf(stderr, " -R Human-readable output with summary (default: CSV)\n"); |
| 2236 | fprintf(stderr, "\n"); |
| 2237 | fprintf(stderr, "OpenMP Thread Affinity (environment variables):\n"); |
| 2238 | fprintf(stderr, " OMP_PROC_BIND=spread Spread threads across NUMA nodes (default)\n"); |
| 2239 | fprintf(stderr, " OMP_PLACES=cores One thread per physical core\n"); |
| 2240 | fprintf(stderr, " OMP_NUM_THREADS=N Override thread count\n"); |
| 2241 | fprintf(stderr, "\n"); |
| 2242 | fprintf(stderr, "Output: CSV to stdout with columns:\n"); |
| 2243 | fprintf(stderr, " size_kb - Per-thread buffer size (KB)\n"); |
| 2244 | fprintf(stderr, " operation - read, write, copy, or latency\n"); |
| 2245 | fprintf(stderr, " bandwidth_mb_s - Aggregate bandwidth in MB/s (0 for latency)\n"); |
| 2246 | fprintf(stderr, " latency_ns - Median memory latency in ns (0 for bandwidth)\n"); |
| 2247 | fprintf(stderr, " latency_stddev_ns - Latency standard deviation in ns (0 for bandwidth)\n"); |
| 2248 | fprintf(stderr, " latency_samples - Number of samples for latency measurement\n"); |
| 2249 | fprintf(stderr, " threads - Thread count used\n"); |
| 2250 | fprintf(stderr, " iterations - Iterations performed\n"); |
| 2251 | fprintf(stderr, " elapsed_s - Elapsed time in seconds\n"); |
| 2252 | fprintf(stderr, "\n"); |
| 2253 | fprintf(stderr, "Latency measurement uses linked list traversal with random node order\n"); |
| 2254 | fprintf(stderr, "to defeat prefetchers. Statistical validity ensured via multiple samples\n"); |
| 2255 | fprintf(stderr, "until coefficient of variation < 5%% or max samples reached.\n"); |
| 2256 | fprintf(stderr, "\n"); |
| 2257 | fprintf(stderr, "Memory model: each thread gets its own buffer.\n"); |
| 2258 | fprintf(stderr, "Total memory = size_kb × threads (×2 for copy: src + dst).\n"); |
| 2259 | fprintf(stderr, "\n"); |
| 2260 | fprintf(stderr, "Compile with -DUSE_NUMA -lnuma for explicit NUMA allocation.\n"); |
| 2261 | } |
| 2262 | |
| 2263 | int main(int argc, char *argv[]) { |
| 2264 | int opt; |
| 2265 | int ops_specified = 0; /* Track if -o was used */ |
| 2266 | |
| 2267 | while ((opt = getopt(argc, argv, "hvfas:t:r:p:o:VHR")) != -1) { |
| 2268 | switch (opt) { |
| 2269 | case 'h': |
| 2270 | usage(argv[0]); |
| 2271 | return 0; |
| 2272 | case 'V': |
| 2273 | printf("%s\n", VERSION); |
| 2274 | return 0; |
| 2275 | case 'v': |
| 2276 | g_verbose++; |
| 2277 | break; |
| 2278 | case 'f': |
| 2279 | g_full_sweep = 1; |
| 2280 | break; |
| 2281 | case 'a': |
| 2282 | g_auto_scaling = 1; |
| 2283 | break; |
| 2284 | case 'r': |
| 2285 | g_benchmark_tries = atoi(optarg); |
| 2286 | if (g_benchmark_tries < 1) g_benchmark_tries = 1; |
| 2287 | break; |
| 2288 | case 'p': |
| 2289 | g_explicit_threads = atoi(optarg); |
| 2290 | if (g_explicit_threads < 1) { |
| 2291 | fprintf(stderr, "Invalid thread count: %s\n", optarg); |
| 2292 | return 1; |
| 2293 | } |
| 2294 | break; |
| 2295 | case 's': { |
| 2296 | long size_kb = atol(optarg); |
| 2297 | if (size_kb <= 0) { |
| 2298 | fprintf(stderr, "Invalid size: %s\n", optarg); |
| 2299 | return 1; |
| 2300 | } |
| 2301 | g_single_size = (size_t)size_kb * 1024; /* Convert KB to bytes */ |
| 2302 | break; |
| 2303 | } |
| 2304 | case 't': |
| 2305 | g_max_runtime = atof(optarg); |
| 2306 | if (g_max_runtime < 0) { |
| 2307 | fprintf(stderr, "Invalid runtime: %s (use 0 for unlimited)\n", optarg); |
| 2308 | return 1; |
| 2309 | } |
| 2310 | break; |
| 2311 | case 'o': { |
| 2312 | /* First -o clears the default "all" mask */ |
| 2313 | if (!ops_specified) { |
| 2314 | g_ops_mask = 0; |
| 2315 | ops_specified = 1; |
| 2316 | } |
| 2317 | /* Parse operation name */ |
| 2318 | if (strcmp(optarg, "read") == 0) { |
| 2319 | g_ops_mask |= (1 << OP_READ); |
| 2320 | } else if (strcmp(optarg, "write") == 0) { |
| 2321 | g_ops_mask |= (1 << OP_WRITE); |
| 2322 | } else if (strcmp(optarg, "copy") == 0) { |
| 2323 | g_ops_mask |= (1 << OP_COPY); |
| 2324 | } else if (strcmp(optarg, "latency") == 0) { |
| 2325 | g_ops_mask |= (1 << OP_LATENCY); |
| 2326 | } else { |
| 2327 | fprintf(stderr, "Invalid operation: %s (use: read, write, copy, latency)\n", optarg); |
| 2328 | return 1; |
| 2329 | } |
| 2330 | break; |
| 2331 | } |
| 2332 | case 'H': |
| 2333 | g_use_hugepages = 1; |
| 2334 | break; |
| 2335 | case 'R': |
| 2336 | g_human_readable = 1; |
| 2337 | break; |
| 2338 | default: |
| 2339 | usage(argv[0]); |
| 2340 | return 1; |
| 2341 | } |
| 2342 | } |
| 2343 | |
| 2344 | /* Initialize */ |
| 2345 | srand((unsigned int)time(NULL)); /* Seed RNG for pointer chain randomization */ |
| 2346 | init_system_info(); |
| 2347 | init_numa(); |
| 2348 | |
| 2349 | /* Run benchmarks */ |
| 2350 | run_all_benchmarks(); |
| 2351 | |
| 2352 | /* Cleanup */ |
| 2353 | cleanup_hwloc(); |
| 2354 | |
| 2355 | return 0; |
| 2356 | } |