| 1 | # sc-membench - Memory Bandwidth Benchmark |
| 2 | |
| 3 | A portable, multi-platform memory bandwidth benchmark designed for comprehensive system analysis. |
| 4 | |
| 5 | ## Features |
| 6 | |
| 7 | - **Multi-platform**: Works on x86, arm64, and other architectures |
| 8 | - **Multiple operations**: Measures read, write, copy bandwidth + memory latency |
| 9 | - **OpenMP parallelization**: Uses OpenMP for efficient multi-threaded bandwidth measurement |
| 10 | - **NUMA-aware**: Automatically handles NUMA systems with `proc_bind(spread)` thread placement |
| 11 | - **Cache-aware sizing**: Adaptive test sizes based on detected L1, L2, L3 cache hierarchy |
| 12 | - **Per-thread buffer model**: Like bw_mem, each thread gets its own buffer |
| 13 | - **Thread control**: Default uses all CPUs; optional auto-scaling to find optimal thread count |
| 14 | - **Latency measurement**: True memory latency using pointer chasing with statistical sampling |
| 15 | - **Statistically valid**: Latency reports median, stddev, and sample count (CV < 5%) |
| 16 | - **Best-of-N runs**: Bandwidth tests run multiple times, reports best result (like lmbench) |
| 17 | - **CSV output**: Machine-readable output for analysis |
| 18 | |
| 19 | ## Quick Start |
| 20 | |
| 21 | ```bash |
| 22 | # Compile |
| 23 | make |
| 24 | |
| 25 | # Run with default settings (uses all CPUs, cache-aware sizes) |
| 26 | ./membench |
| 27 | |
| 28 | # Run with verbose output and 5 minute time limit |
| 29 | ./membench -v -t 300 |
| 30 | |
| 31 | # Test specific buffer size (1MB per thread) |
| 32 | ./membench -s 1024 |
| 33 | |
| 34 | # Compile with NUMA support (requires libnuma-dev) |
| 35 | make numa |
| 36 | ./membench-numa -v |
| 37 | ``` |
| 38 | |
| 39 | ## Docker Usage |
| 40 | |
| 41 | The easiest way to run sc-membench without building is using the pre-built Docker image: |
| 42 | |
| 43 | ```bash |
| 44 | # Run with default settings |
| 45 | docker run --rm ghcr.io/sparecores/membench:main |
| 46 | |
| 47 | # Run with verbose output and time limit |
| 48 | docker run --rm ghcr.io/sparecores/membench:main -v -t 300 |
| 49 | |
| 50 | # Test specific buffer size |
| 51 | docker run --rm ghcr.io/sparecores/membench:main -s 1024 |
| 52 | |
| 53 | # Recommended: use --privileged and huge pages for best accuracy |
| 54 | docker run --rm --privileged ghcr.io/sparecores/membench:main -H -v |
| 55 | |
| 56 | # Save output to file |
| 57 | docker run --rm --privileged ghcr.io/sparecores/membench:main -H > results.csv |
| 58 | ``` |
| 59 | |
| 60 | **Notes:** |
| 61 | - The `--privileged` flag is recommended for optimal CPU pinning and NUMA support |
| 62 | - The `-H` flag enables huge pages automatically for large buffers (≥ 2× huge page size), no setup required |
| 63 | |
| 64 | ## Packaging |
| 65 | |
| 66 | sc-membench is packaged in some distributions. For current packaging status and version information across repositories, see [repology.org/project/sc-membench/versions](https://repology.org/project/sc-membench/versions). |
| 67 | |
| 68 | ## Build Options |
| 69 | |
| 70 | ```bash |
| 71 | make # Basic version (sysfs cache detection, Linux only) |
| 72 | make hwloc # With hwloc 2 (recommended - portable cache detection) |
| 73 | make numa # With NUMA support |
| 74 | make full # With hwloc + NUMA (recommended for servers) |
| 75 | make all # Build all versions |
| 76 | make clean # Remove built files |
| 77 | make test # Quick 30-second test run |
| 78 | ``` |
| 79 | |
| 80 | ### Recommended Build |
| 81 | |
| 82 | For production use on servers, build with all features: |
| 83 | |
| 84 | ```bash |
| 85 | # Install dependencies first |
| 86 | sudo apt-get install libhugetlbfs-dev libhwloc-dev libnuma-dev # Debian/Ubuntu |
| 87 | # or: sudo yum install libhugetlbfs-devel hwloc-devel numactl-devel # RHEL/CentOS |
| 88 | |
| 89 | # Build with full features |
| 90 | make full |
| 91 | ./membench-full -v |
| 92 | ``` |
| 93 | |
| 94 | ## Usage |
| 95 | |
| 96 | ``` |
| 97 | sc-membench - Memory Bandwidth Benchmark |
| 98 | |
| 99 | Usage: ./membench [options] |
| 100 | |
| 101 | Options: |
| 102 | -h Show help |
| 103 | -v Verbose output (use -vv for more detail) |
| 104 | -s SIZE_KB Test only this buffer size (in KB), e.g. -s 1024 for 1MB |
| 105 | -r TRIES Repeat each test N times, report best (default: 3) |
| 106 | -f Full sweep (test larger sizes up to memory limit) |
| 107 | -p THREADS Use exactly this many threads (default: num_cpus) |
| 108 | -a Auto-scaling: try different thread counts to find best |
| 109 | (slower but finds optimal thread count per buffer size) |
| 110 | -t SECONDS Maximum runtime, 0 = unlimited (default: unlimited) |
| 111 | -o OP Run only this operation: read, write, copy, or latency |
| 112 | Can be specified multiple times (default: all) |
| 113 | -H Enable huge pages for large buffers (>= 2x huge page size) |
| 114 | Uses THP automatically, no setup required |
| 115 | -R Human-readable output with summary and benchmark scores |
| 116 | (default: CSV output) |
| 117 | ``` |
| 118 | |
| 119 | ## Output Format |
| 120 | |
| 121 | CSV output to stdout with columns: |
| 122 | |
| 123 | | Column | Description | |
| 124 | |--------|-------------| |
| 125 | | `size_kb` | **Per-thread** buffer size (KB) | |
| 126 | | `operation` | Operation type: `read`, `write`, `copy`, or `latency` | |
| 127 | | `bandwidth_mb_s` | Aggregate bandwidth across all threads (MB/s), 0 for latency | |
| 128 | | `latency_ns` | Median memory latency (nanoseconds), 0 for bandwidth tests | |
| 129 | | `latency_stddev_ns` | Standard deviation of latency samples (nanoseconds), 0 for bandwidth | |
| 130 | | `latency_samples` | Number of samples collected for latency measurement, 0 for bandwidth | |
| 131 | | `threads` | Thread count used | |
| 132 | | `iterations` | Number of iterations performed | |
| 133 | | `elapsed_s` | Elapsed time for the test (seconds) | |
| 134 | |
| 135 | **Total memory used** = `size_kb × threads` (or `× 2` for copy which needs src + dst). |
| 136 | |
| 137 | ### Example Output |
| 138 | |
| 139 | ```csv |
| 140 | size_kb,operation,bandwidth_mb_s,latency_ns,latency_stddev_ns,latency_samples,threads,iterations,elapsed_s |
| 141 | 32,read,9309701.64,0,0,0,96,292056,0.094113 |
| 142 | 32,write,9868845.93,0,0,0,96,578703,0.175918 |
| 143 | 32,latency,0,1.77,0.00,7,1,7,0.254053 |
| 144 | 128,read,6410473.70,0,0,0,96,83556,0.156412 |
| 145 | 128,write,9883443.78,0,0,0,96,177556,0.215580 |
| 146 | 128,latency,0,3.93,0.00,7,1,7,0.689736 |
| 147 | 512,latency,0,5.66,0.01,7,1,7,0.654846 |
| 148 | 1024,latency,0,7.38,0.04,7,1,7,0.671615 |
| 149 | 32768,latency,0,44.90,0.03,7,1,7,1.050579 |
| 150 | 131072,latency,0,96.78,3.00,7,1,7,8.520152 |
| 151 | 262144,latency,0,122.22,0.90,7,1,7,21.756578 |
| 152 | ``` |
| 153 | |
| 154 | In this example ([Azure D96pls_v6](https://sparecores.com/server/azure/Standard_D96pls_v6) with 96 ARM cores, 64KB L1, 1MB L2, 128MB L3): |
| 155 | - **32KB**: Fits in L1 → very high bandwidth (~9.3 TB/s read), low latency (~1.8ns, stddev 0.00) |
| 156 | - **512KB**: Fits in L2 → good latency (~5.7ns, stddev 0.01) |
| 157 | - **32MB**: In L3 → moderate latency (~45ns, stddev 0.03) |
| 158 | - **128MB**: At L3 boundary → RAM latency visible (~97ns, stddev 3.0) |
| 159 | - **256MB**: Past L3 → pure RAM latency (~122ns, stddev 0.9) |
| 160 | |
| 161 | ## Human-Readable Output (`-R`) |
| 162 | |
| 163 | Use `-R` for a formatted table with summary statistics and benchmark scores instead of CSV: |
| 164 | |
| 165 | ```bash |
| 166 | ./membench -R |
| 167 | ``` |
| 168 | |
| 169 | ### Example Output |
| 170 | |
| 171 | ``` |
| 172 | Size Op Bandwidth Latency Threads |
| 173 | ---- -- --------- ------- ------- |
| 174 | 32 KB read 2.6 TB/s - 32 |
| 175 | 32 KB write 1.6 TB/s - 32 |
| 176 | 32 KB copy 464.4 GB/s - 32 |
| 177 | 32 KB latency - 0.9 ns 1 |
| 178 | 128 KB read 1.7 TB/s - 32 |
| 179 | 128 KB write 691.7 GB/s - 32 |
| 180 | 128 KB copy 495.5 GB/s - 32 |
| 181 | 128 KB latency - 2.4 ns 1 |
| 182 | ... |
| 183 | |
| 184 | ================================================================================ |
| 185 | BENCHMARK SUMMARY |
| 186 | ================================================================================ |
| 187 | |
| 188 | BANDWIDTH (MB/s): |
| 189 | Operation Peak Weighted Avg |
| 190 | --------- ---- ------------ |
| 191 | Read 2612561 1680432 |
| 192 | Write 1605601 850445 |
| 193 | Copy 495476 372027 |
| 194 | |
| 195 | LATENCY: |
| 196 | Best latency: 97.2 ns (RAM) at 131072 KB buffer |
| 197 | |
| 198 | -------------------------------------------------------------------------------- |
| 199 | BENCHMARK SCORE (higher is better): |
| 200 | |
| 201 | Bandwidth Score: 1571.2 (avg peak bandwidth in GB/s) |
| 202 | Latency Score: 10.3 (1000 / latency_ns) |
| 203 | |
| 204 | >> COMBINED SCORE: 4024 (sqrt(bw_score × latency_score) × 100) |
| 205 | -------------------------------------------------------------------------------- |
| 206 | ``` |
| 207 | |
| 208 | ### Summary Statistics |
| 209 | |
| 210 | | Metric | Description | |
| 211 | |--------|-------------| |
| 212 | | **Peak** | Highest bandwidth achieved across all buffer sizes | |
| 213 | | **Weighted Avg** | Average weighted by log₂(size) — larger buffers count more | |
| 214 | | **Best latency** | Latency at the largest buffer size tested (closest to true RAM latency) | |
| 215 | |
| 216 | ### Benchmark Scores |
| 217 | |
| 218 | The summary includes scores for easy comparison between systems: |
| 219 | |
| 220 | | Score | Formula | Description | |
| 221 | |-------|---------|-------------| |
| 222 | | **Bandwidth Score** | `avg(peak_read, peak_write, peak_copy) / 1000` | Average peak bandwidth in GB/s | |
| 223 | | **Latency Score** | `1000 / latency_ns` | Inverse of RAM latency (higher = faster) | |
| 224 | | **Combined Score** | `sqrt(bw_score × latency_score) × 100` | Geometric mean of both (balanced) | |
| 225 | |
| 226 | The **Combined Score** uses a geometric mean so that neither bandwidth nor latency dominates — both contribute equally to the final score. |
| 227 | |
| 228 | ### Score Comparability Warning |
| 229 | |
| 230 | When using options that affect test coverage, a warning is displayed: |
| 231 | |
| 232 | ``` |
| 233 | WARNING: Scores may not be comparable due to non-default options: |
| 234 | - Time limit (-t 60) may have prevented testing larger buffer sizes |
| 235 | - Fixed thread count (-p 4) instead of using all CPUs (32) |
| 236 | For comparable scores, run without -t, -p, or -s options. |
| 237 | ``` |
| 238 | |
| 239 | **For comparable benchmark scores**, run without `-t`, `-p`, or `-s` options to ensure: |
| 240 | - All buffer sizes are tested (including large RAM-sized buffers) |
| 241 | - All CPUs are utilized (maximum bandwidth) |
| 242 | - Full cache hierarchy is exercised |
| 243 | |
| 244 | ## Operations Explained |
| 245 | |
| 246 | ### Read (`read`) |
| 247 | Reads all 64-bit words from the buffer using XOR (faster than addition, no carry chains). This measures pure read bandwidth. |
| 248 | |
| 249 | ```c |
| 250 | checksum ^= buffer[i]; // For all elements, using 8 independent accumulators |
| 251 | ``` |
| 252 | |
| 253 | ### Write (`write`) |
| 254 | Writes a pattern to all 64-bit words in the buffer. This measures pure write bandwidth. |
| 255 | |
| 256 | ```c |
| 257 | buffer[i] = pattern; // For all elements |
| 258 | ``` |
| 259 | |
| 260 | ### Copy (`copy`) |
| 261 | Copies data from source to destination buffer. Reports bandwidth as `buffer_size / time` (matching lmbench's approach), not `2 × buffer_size / time`. |
| 262 | |
| 263 | ```c |
| 264 | dst[i] = src[i]; // For all elements |
| 265 | ``` |
| 266 | |
| 267 | **Note:** Copy bandwidth is typically lower than read or write alone because it performs both operations. The reported bandwidth represents the buffer size traversed, not total bytes moved (read + write). |
| 268 | |
| 269 | ### Latency (`latency`) |
| 270 | Measures true memory access latency using **pointer chasing** with a linked list traversal approach inspired by [ram_bench](https://github.com/emilk/ram_bench) by Emil Ernerfeldt. Each memory access depends on the previous one, preventing CPU pipelining and prefetching. |
| 271 | |
| 272 | ```c |
| 273 | // Node structure (16 bytes) - realistic for linked list traversal |
| 274 | struct Node { |
| 275 | uint64_t payload; // Dummy data for realistic cache behavior |
| 276 | Node *next; // Pointer to next node |
| 277 | }; |
| 278 | |
| 279 | // Each load depends on previous (can't be optimized away) |
| 280 | node = node->next; // Address comes from previous load |
| 281 | ``` |
| 282 | |
| 283 | The buffer is initialized as a contiguous array of nodes linked in **randomized order** to defeat hardware prefetchers. This measures: |
| 284 | - L1/L2/L3 cache hit latency at small sizes |
| 285 | - DRAM access latency at large sizes |
| 286 | - True memory latency without pipelining effects |
| 287 | |
| 288 | **Statistical validity**: The latency measurement collects **multiple independent samples** (7-21) and reports the **median** (robust to outliers) along with standard deviation. Sampling continues until coefficient of variation < 5% or maximum samples reached. |
| 289 | |
| 290 | **CPU and NUMA pinning**: The latency test pins to CPU 0 and allocates memory on the local NUMA node (when compiled with NUMA support) for consistent, reproducible results. |
| 291 | |
| 292 | Results are reported in **nanoseconds per access** with statistical measures: |
| 293 | - `latency_ns`: Median latency (robust central tendency) |
| 294 | - `latency_stddev_ns`: Standard deviation (measurement precision indicator) |
| 295 | - `latency_samples`: Number of samples collected (statistical effort) |
| 296 | |
| 297 | **Large L3 cache support**: The latency test uses buffers up to 2GB (or 25% of RAM) to correctly measure DRAM latency even on processors with huge L3 caches like AMD EPYC 9754 (1.1GB L3 with 3D V-Cache). |
| 298 | |
| 299 | ## Memory Sizes Tested |
| 300 | |
| 301 | The benchmark tests **per-thread buffer sizes** at cache transition points, automatically adapting to the detected cache hierarchy: |
| 302 | |
| 303 | ### Adaptive Cache-Aware Sizes |
| 304 | |
| 305 | Based on detected L1, L2, L3 cache sizes (typically 10 sizes): |
| 306 | |
| 307 | | Size | Purpose | |
| 308 | |------|---------| |
| 309 | | L1/2 | Pure L1 cache performance (e.g., 32KB for 64KB L1) | |
| 310 | | 2×L1 | L1→L2 transition | |
| 311 | | L2/2 | Mid L2 cache performance | |
| 312 | | L2 | L2 cache boundary | |
| 313 | | 2×L2 | L2→L3 transition | |
| 314 | | L3/4 | Mid L3 cache (for large L3 caches) | |
| 315 | | L3/2 | Late L3 cache | |
| 316 | | L3 | L3→RAM boundary | |
| 317 | | 2×L3 | Past L3, hitting RAM | |
| 318 | | 4×L3 | Deep into RAM | |
| 319 | |
| 320 | With `-f` (full sweep), additional larger sizes are tested up to the memory limit. |
| 321 | |
| 322 | ### Cache Detection |
| 323 | |
| 324 | With hwloc 2 (recommended), cache sizes are detected automatically on any platform. |
| 325 | Without hwloc, the benchmark uses sysctl (macOS/BSD) or parses `/sys/devices/system/cpu/*/cache/` (Linux). |
| 326 | |
| 327 | If cache detection fails, sensible defaults are used (32KB L1, 256KB L2, 8MB L3). |
| 328 | |
| 329 | ## Thread Model (Per-Thread Buffers) |
| 330 | |
| 331 | Like bw_mem, each thread gets its **own private buffer**: |
| 332 | |
| 333 | ``` |
| 334 | Example for 1MB buffer size with 4 threads (read/write): |
| 335 | Thread 0: 1MB buffer |
| 336 | Thread 1: 1MB buffer |
| 337 | Thread 2: 1MB buffer |
| 338 | Thread 3: 1MB buffer |
| 339 | Total memory: 4MB |
| 340 | |
| 341 | Example for 1MB buffer size with 4 threads (copy): |
| 342 | Thread 0: 1MB src + 1MB dst = 2MB |
| 343 | Thread 1: 1MB src + 1MB dst = 2MB |
| 344 | ... |
| 345 | Total memory: 8MB |
| 346 | ``` |
| 347 | |
| 348 | ### Thread Modes |
| 349 | |
| 350 | | Mode | Flag | Behavior | |
| 351 | |------|------|----------| |
| 352 | | **Default** | (none) | Use `num_cpus` threads | |
| 353 | | **Explicit** | `-p N` | Use exactly N threads | |
| 354 | | **Auto-scaling** | `-a` | Try 1, 2, 4, ..., num_cpus threads, report best | |
| 355 | |
| 356 | ### OpenMP Thread Affinity |
| 357 | |
| 358 | You can fine-tune thread placement using OpenMP environment variables: |
| 359 | |
| 360 | ```bash |
| 361 | # Spread threads across NUMA nodes (default behavior) |
| 362 | OMP_PROC_BIND=spread OMP_PLACES=cores ./membench |
| 363 | |
| 364 | # Bind threads close together (may reduce bandwidth on multi-socket) |
| 365 | OMP_PROC_BIND=close OMP_PLACES=cores ./membench |
| 366 | |
| 367 | # Override thread count via environment |
| 368 | OMP_NUM_THREADS=8 ./membench |
| 369 | ``` |
| 370 | |
| 371 | | Variable | Values | Effect | |
| 372 | |----------|--------|--------| |
| 373 | | `OMP_PROC_BIND` | `spread`, `close`, `master` | Thread distribution strategy | |
| 374 | | `OMP_PLACES` | `cores`, `threads`, `sockets` | Placement units | |
| 375 | | `OMP_NUM_THREADS` | Integer | Override thread count | |
| 376 | |
| 377 | The default `proc_bind(spread)` in the code distributes threads evenly across NUMA nodes for maximum memory bandwidth. |
| 378 | |
| 379 | ### What the Benchmark Measures |
| 380 | |
| 381 | - **Aggregate bandwidth**: Sum of all threads' bandwidth |
| 382 | - **Per-thread buffer**: Each thread works on its own memory region |
| 383 | - **No sharing**: Threads don't contend for the same cache lines |
| 384 | |
| 385 | ### Interpreting Results |
| 386 | |
| 387 | - `size_kb` = buffer size per thread |
| 388 | - `threads` = number of threads used |
| 389 | - `bandwidth_mb_s` = total system bandwidth (all threads combined) |
| 390 | - Total memory = `size_kb × threads` (×2 for copy) |
| 391 | |
| 392 | ## NUMA Support |
| 393 | |
| 394 | When compiled with `-DUSE_NUMA` and linked with `-lnuma`: |
| 395 | |
| 396 | - Detects NUMA topology automatically |
| 397 | - Maps CPUs to their NUMA nodes |
| 398 | - Load-balances threads across NUMA nodes |
| 399 | - Binds each thread's memory to its local node |
| 400 | - Works transparently on UMA (single-node) systems |
| 401 | |
| 402 | ### NUMA Load Balancing |
| 403 | |
| 404 | On multi-socket systems, OpenMP's `proc_bind(spread)` distributes threads **evenly across NUMA nodes** to ensure balanced utilization of all memory controllers. |
| 405 | |
| 406 | **Example: 128 threads on a 2-node system (96 CPUs per node):** |
| 407 | |
| 408 | ``` |
| 409 | Without spread (may cluster): With proc_bind(spread): |
| 410 | Thread 0-95 → Node 0 (96 threads) Threads spread evenly across nodes |
| 411 | Thread 96-127 → Node 1 (32 threads) ~64 threads per node |
| 412 | Result: Node 0 overloaded! Result: Balanced utilization! |
| 413 | ``` |
| 414 | |
| 415 | **Impact:** |
| 416 | - Higher bandwidth with balanced distribution |
| 417 | - More accurate measurement of total system memory bandwidth |
| 418 | - Exercises all memory controllers evenly |
| 419 | |
| 420 | ### NUMA-Local Memory |
| 421 | |
| 422 | Each thread allocates its buffer directly on its local NUMA node using `numa_alloc_onnode()`: |
| 423 | |
| 424 | ```c |
| 425 | // Inside OpenMP parallel region with proc_bind(spread) |
| 426 | int cpu = sched_getcpu(); |
| 427 | int node = numa_node_of_cpu(cpu); |
| 428 | buffer = numa_alloc_onnode(size, node); |
| 429 | ``` |
| 430 | |
| 431 | This ensures: |
| 432 | - Memory is allocated on the same node as the accessing CPU |
| 433 | - No cross-node memory access penalties |
| 434 | - No memory migrations during the benchmark |
| 435 | |
| 436 | ### Verbose Output |
| 437 | |
| 438 | Use `-v` to see the detected NUMA topology: |
| 439 | |
| 440 | ``` |
| 441 | NUMA: 2 nodes detected (libnuma enabled) |
| 442 | NUMA topology: |
| 443 | Node 0: 96 CPUs (first: 0, last: 95) |
| 444 | Node 1: 96 CPUs (first: 96, last: 191) |
| 445 | ``` |
| 446 | |
| 447 | ## Huge Pages Support |
| 448 | |
| 449 | Use `-H` to enable huge pages (2MB instead of 4KB). This reduces TLB (Translation Lookaside Buffer) pressure, which is especially beneficial for: |
| 450 | |
| 451 | - **Large buffer tests**: A 2GB buffer needs 512K page table entries with 4KB pages, but only 1024 with 2MB huge pages |
| 452 | - **Latency tests**: Random pointer-chasing access patterns cause many TLB misses with small pages |
| 453 | - **Accurate measurements**: TLB overhead can distort results, making memory appear slower than it is |
| 454 | |
| 455 | ### Automatic and smart |
| 456 | |
| 457 | The `-H` option is designed to "just work": |
| 458 | |
| 459 | 1. **Automatic threshold**: Huge pages are only used for buffers ≥ 2× huge page size (typically 4MB on systems with 2MB huge pages). The huge page size is detected dynamically via `libhugetlbfs`. Smaller buffers use regular pages automatically (no wasted memory, no user intervention needed). |
| 460 | |
| 461 | 2. **No setup required**: The benchmark uses **Transparent Huge Pages (THP)** via `madvise(MADV_HUGEPAGE)`, which is handled automatically by the Linux kernel. No root access or pre-allocation needed. |
| 462 | |
| 463 | 3. **Graceful fallback**: If THP isn't available, the benchmark falls back to regular pages transparently. |
| 464 | |
| 465 | ### How it works |
| 466 | |
| 467 | When `-H` is enabled and buffer size ≥ threshold (2× huge page size): |
| 468 | |
| 469 | 1. **First tries explicit huge pages** (`MAP_HUGETLB`) for deterministic huge pages |
| 470 | 2. **Falls back to THP** (`madvise(MADV_HUGEPAGE)`) which works without pre-configuration |
| 471 | 3. **Falls back to regular pages** if neither is available |
| 472 | |
| 473 | ### Optional: Pre-allocating explicit huge pages |
| 474 | |
| 475 | For the most deterministic results, you can pre-allocate explicit huge pages: |
| 476 | |
| 477 | ```bash |
| 478 | # Check current huge page status |
| 479 | grep Huge /proc/meminfo |
| 480 | |
| 481 | # Calculate huge pages needed for BANDWIDTH tests (read/write/copy): |
| 482 | # threads × buffer_size × 2 (for copy: src+dst) / 2MB |
| 483 | # |
| 484 | # Examples: |
| 485 | # 8 CPUs, 256 MiB buffer: 8 × 256 × 2 / 2 = 2,048 pages (4 GB) |
| 486 | # 64 CPUs, 256 MiB buffer: 64 × 256 × 2 / 2 = 16,384 pages (32 GB) |
| 487 | # 192 CPUs, 256 MiB buffer: 192 × 256 × 2 / 2 = 49,152 pages (96 GB) |
| 488 | # |
| 489 | # LATENCY tests run single-threaded, so need much less: |
| 490 | # 256 MiB buffer: 256 / 2 = 128 pages (256 MB) |
| 491 | |
| 492 | # Allocate huge pages (requires root) - adjust for your system |
| 493 | echo 49152 | sudo tee /proc/sys/vm/nr_hugepages |
| 494 | |
| 495 | # Run with huge pages (will use explicit huge pages if available) |
| 496 | ./membench -H -v |
| 497 | ``` |
| 498 | |
| 499 | However, this is **optional** - THP works well for most use cases without any setup, and doesn't require pre-allocation. If explicit huge pages run out, the benchmark automatically falls back to THP. |
| 500 | |
| 501 | ### Usage recommendation |
| 502 | |
| 503 | Just add `-H` to your command line - the benchmark handles everything automatically: |
| 504 | |
| 505 | ```bash |
| 506 | # Recommended for production benchmarking |
| 507 | ./membench -H |
| 508 | |
| 509 | # With verbose output to see what's happening |
| 510 | ./membench -H -v |
| 511 | ``` |
| 512 | |
| 513 | The benchmark will use huge pages only where they help (large buffers) and regular pages where they don't (small buffers). |
| 514 | |
| 515 | ### Why latency improves more than bandwidth |
| 516 | |
| 517 | You may notice that `-H` dramatically improves latency measurements (often 20-40% lower) while bandwidth stays roughly the same. This is expected: |
| 518 | |
| 519 | **Latency tests** use pointer chasing - random jumps through memory. Each access requires address translation via the TLB (Translation Lookaside Buffer): |
| 520 | |
| 521 | | Buffer Size | 4KB pages | 2MB huge pages | |
| 522 | |-------------|-----------|----------------| |
| 523 | | 128 MB | 32,768 pages | 64 pages | |
| 524 | | TLB fit? | No (TLB ~1000-2000 entries) | Yes | |
| 525 | | TLB misses | Frequent | Rare | |
| 526 | |
| 527 | With 4KB pages on a 128MB buffer: |
| 528 | - 32,768 pages can't fit in the TLB |
| 529 | - Random pointer chasing causes frequent TLB misses |
| 530 | - Each TLB miss adds **10-20+ CPU cycles** (page table walk) |
| 531 | - Measured latency = true memory latency + TLB overhead |
| 532 | |
| 533 | With 2MB huge pages: |
| 534 | - Only 64 pages easily fit in the TLB |
| 535 | - Almost no TLB misses |
| 536 | - Measured latency ≈ **true memory latency** |
| 537 | |
| 538 | ### Real-world benchmark results |
| 539 | |
| 540 | #### Azure D96pls_v6 (ARM) |
| 541 | |
| 542 | Measured on [**Azure D96pls_v6**](https://sparecores.com/server/azure/Standard_D96pls_v6) (96 ARM Neoverse-N2 cores, 2 NUMA nodes, L1d=64KB/core, L2=1MB/core, L3=128MB shared): |
| 543 | |
| 544 | | Buffer | No Huge Pages | With THP (-H) | Improvement | |
| 545 | |--------|---------------|---------------|-------------| |
| 546 | | 32 KB | 1.77 ns | 1.77 ns | HP not used (< 4MB) | |
| 547 | | 128 KB | 3.95 ns | 3.95 ns | HP not used (< 4MB) | |
| 548 | | 512 KB | 5.99 ns | 5.98 ns | HP not used (< 4MB) | |
| 549 | | 1 MB | 11.52 ns | 10.92 ns | HP not used (< 4MB) | |
| 550 | | 2 MB | 24.27 ns | 24.65 ns | HP not used (< 4MB) | |
| 551 | | **32 MB** | 44.90 ns | **36.23 ns** | **-19%** | |
| 552 | | **64 MB** | 49.40 ns | **40.77 ns** | **-17%** | |
| 553 | | **128 MB** | 92.50 ns | **78.32 ns** | **-15%** | |
| 554 | | **256 MB** | 121.92 ns | **107.65 ns** | **-12%** | |
| 555 | | **512 MB** | 140.97 ns | **118.74 ns** | **-16%** | |
| 556 | |
| 557 | #### AWS c8a.metal-48xl (AMD) |
| 558 | |
| 559 | Measured on [**AWS c8a.metal-48xl**](https://sparecores.com/server/aws/c8a.metal-48xl) (192 AMD EPYC 9R45 cores, 2 NUMA nodes, L1d=48KB/core, L2=1MB/core, L3=32MB/die): |
| 560 | |
| 561 | | Buffer | No Huge Pages | With THP (-H) | Improvement | |
| 562 | |--------|---------------|---------------|-------------| |
| 563 | | 32 KB | 0.89 ns | 0.89 ns | HP not used (< 4MB) | |
| 564 | | 128 KB | 2.43 ns | 2.45 ns | HP not used (< 4MB) | |
| 565 | | 512 KB | 3.32 ns | 3.35 ns | HP not used (< 4MB) | |
| 566 | | 1 MB | 5.47 ns | 4.09 ns | HP not used (< 4MB) | |
| 567 | | 2 MB | 8.85 ns | 8.85 ns | HP not used (< 4MB) | |
| 568 | | **8 MB** | 11.72 ns | **10.32 ns** | **-12%** | |
| 569 | | **16 MB** | 12.58 ns | **10.74 ns** | **-15%** | |
| 570 | | **32 MB** | **30.83 ns** | **11.29 ns** | **-63%** | |
| 571 | | **64 MB** | 84.81 ns | **75.25 ns** | **-11%** | |
| 572 | | **128 MB** | 117.75 ns | **105.45 ns** | **-10%** | |
| 573 | |
| 574 | **Key observations:** |
| 575 | - **Small buffers (≤ 2MB)**: No significant difference — TLB can handle the page count |
| 576 | - **L3 boundary effect**: AMD shows **63% improvement at 32MB** (exactly at L3 size) — without huge pages, TLB misses make L3 appear like RAM! |
| 577 | - **L3 region**: 12-19% improvement with huge pages |
| 578 | - **RAM region**: 10-16% lower latency with huge pages |
| 579 | - **THP works automatically**: No pre-allocation needed, just use `-H` |
| 580 | |
| 581 | **Bottom line**: Use `-H` for accurate latency measurements on large buffers. Without huge pages, TLB overhead can severely distort results, especially at cache boundaries. |
| 582 | |
| 583 | **Bandwidth tests** don't improve as much because: |
| 584 | - Sequential access has better TLB locality (same pages accessed repeatedly) |
| 585 | - Hardware prefetchers hide TLB miss latency |
| 586 | - The memory bus is already saturated |
| 587 | |
| 588 | ## Consistent Results |
| 589 | |
| 590 | Achieving consistent benchmark results on modern multi-core systems requires careful handling of: |
| 591 | |
| 592 | ### Thread Pinning |
| 593 | |
| 594 | Threads are distributed across CPUs using OpenMP's `proc_bind(spread)` clause, which spreads threads evenly across NUMA nodes and physical cores. This prevents the OS scheduler from migrating threads between cores, which causes huge variability. |
| 595 | |
| 596 | ### NUMA-Aware Memory |
| 597 | |
| 598 | On NUMA systems, each thread allocates memory directly on its local NUMA node using `numa_alloc_onnode()`. OpenMP's `proc_bind(spread)` ensures threads are distributed across NUMA nodes, then each thread allocates locally. This ensures: |
| 599 | - Memory is close to where it will be accessed |
| 600 | - No cross-node memory access penalties |
| 601 | - No memory migrations during the benchmark |
| 602 | |
| 603 | ### Bandwidth: Best-of-N Runs |
| 604 | |
| 605 | Like lmbench (TRIES=11), each bandwidth test configuration runs multiple times and reports the best result: |
| 606 | |
| 607 | 1. First run is a warmup (discarded) to stabilize CPU frequency |
| 608 | 2. Each configuration is then tested 3 times (configurable with `-r`) |
| 609 | 3. Highest bandwidth is reported (best shows true hardware capability) |
| 610 | |
| 611 | ### Latency: Statistical Sampling |
| 612 | |
| 613 | Latency measurements use a different approach optimized for statistical validity: |
| 614 | |
| 615 | 1. Thread is pinned to CPU 0 with NUMA-local memory |
| 616 | 2. Multiple independent samples (7-21) are collected per measurement |
| 617 | 3. Sampling continues until coefficient of variation < 5% or max samples reached |
| 618 | 4. **Median** latency is reported (robust to outliers) |
| 619 | 5. Standard deviation and sample count are included for validation |
| 620 | |
| 621 | ### Result |
| 622 | |
| 623 | With these optimizations, benchmark variability is typically **<1%** (compared to 30-60% without them). |
| 624 | |
| 625 | ### Configuration |
| 626 | |
| 627 | ```bash |
| 628 | ./membench -r 5 # Run each test 5 times instead of 3 |
| 629 | ./membench -r 1 # Single run (fastest, still consistent due to pinning) |
| 630 | ./membench -p 16 # Use exactly 16 threads |
| 631 | ./membench -a # Auto-scale to find optimal thread count |
| 632 | ``` |
| 633 | |
| 634 | ## Comparison with lmbench |
| 635 | |
| 636 | ### Bandwidth (bw_mem) |
| 637 | |
| 638 | | Aspect | sc-membench | lmbench bw_mem | |
| 639 | |--------|-------------|----------------| |
| 640 | | **Parallelism model** | OpenMP threads | Processes (fork) | |
| 641 | | **Buffer allocation** | Each thread has own buffer | Each process has own buffer | |
| 642 | | **Size reporting** | Per-thread buffer size | Per-process buffer size | |
| 643 | | **Read operation** | Reads 100% of data | `rd` reads 25% (strided) | |
| 644 | | **Copy reporting** | Buffer size / time | Buffer size / time | |
| 645 | | **Huge pages** | Built-in (`-H` flag) | Not supported (uses `valloc`) | |
| 646 | | **Operation selection** | `-o read/write/copy/latency` | Separate invocations per operation | |
| 647 | | **Output format** | CSV (stdout) | Text to stderr | |
| 648 | | **Full vs strided read** | Always 100% (`read`) | `rd` (25% strided) or `frd` (100%) | |
| 649 | |
| 650 | **Key differences:** |
| 651 | |
| 652 | 1. **Size meaning**: Both report per-worker buffer size (comparable) |
| 653 | 2. **Read operation**: bw_mem `rd` uses 32-byte stride (reads 25% of data at indices 0,4,8...124 per 512-byte chunk), reporting ~4x higher apparent bandwidth. Use `frd` for full read. sc-membench always reads 100%. |
| 654 | 3. **Thread control**: sc-membench defaults to num_cpus threads; use `-a` for auto-scaling or `-p N` for explicit count |
| 655 | 4. **Huge pages**: sc-membench has built-in support (`-H`) with automatic THP fallback; lmbench has no huge page support |
| 656 | 5. **Workflow**: sc-membench runs all tests in one invocation; bw_mem requires separate runs per operation (`bw_mem 64m rd`, `bw_mem 64m wr`, etc.) |
| 657 | |
| 658 | ### Latency (lat_mem_rd) |
| 659 | |
| 660 | sc-membench's `latency` operation is comparable to lmbench's `lat_mem_rd`: |
| 661 | |
| 662 | | Aspect | sc-membench latency | lmbench lat_mem_rd | |
| 663 | |--------|---------------------|-------------------| |
| 664 | | **Method** | Pointer chasing (linked list) | Pointer chasing (array) | |
| 665 | | **Node structure** | 16 bytes (payload + pointer) | 8 bytes (pointer only) | |
| 666 | | **Pointer order** | Randomized (defeats prefetching) | Fixed backward stride (may be prefetched) | |
| 667 | | **Stride** | Random (visits all elements) | Configurable (default 64 bytes on 64-bit) | |
| 668 | | **Statistical validity** | Multiple samples, reports median + stddev | Single measurement | |
| 669 | | **CPU/NUMA pinning** | Pins to CPU 0, NUMA-local memory | No pinning | |
| 670 | | **Output** | Median nanoseconds + stddev + sample count | Nanoseconds | |
| 671 | | **Huge pages** | Built-in (`-H` flag) | Not supported | |
| 672 | |
| 673 | Both measure memory latency using dependent loads that prevent pipelining. |
| 674 | |
| 675 | **Key differences**: |
| 676 | |
| 677 | 1. **Prefetching vulnerability**: lat_mem_rd uses fixed backward stride, which modern CPUs may prefetch (the man page acknowledges: "vulnerable to smart, stride-sensitive cache prefetching policies"). sc-membench's randomized pointer chain defeats all prefetching, measuring true random-access latency. |
| 678 | |
| 679 | 2. **Statistical validity**: sc-membench collects 7-21 samples per measurement, reports median (robust to outliers) and standard deviation, and continues until coefficient of variation < 5%. This provides confidence in the results. |
| 680 | |
| 681 | 3. **Reproducibility**: CPU pinning and NUMA-local memory allocation eliminate variability from thread migration and remote memory access. |
| 682 | |
| 683 | **Huge pages advantage**: With `-H`, sc-membench automatically uses huge pages for large buffers, eliminating TLB overhead that can inflate latency by 20-40% (see [benchmark results](#real-world-benchmark-results)). |
| 684 | |
| 685 | ## Interpreting Results |
| 686 | |
| 687 | ### Cache Effects |
| 688 | Look for bandwidth drops and latency increases as buffer sizes exceed cache levels: |
| 689 | - Dramatic change at L1 boundary (32-64KB per thread typically) |
| 690 | - Another change at L2 boundary (256KB-1MB per thread typically) |
| 691 | - Final change when total memory exceeds L3 (depends on thread count) |
| 692 | |
| 693 | ### Thread Configuration |
| 694 | - By default, all CPUs are used for maximum aggregate bandwidth |
| 695 | - Use `-p N` to test with a specific thread count |
| 696 | - Use `-a` to find optimal thread count (slower but thorough) |
| 697 | - Latency test: Always uses 1 thread (measures true access latency) |
| 698 | |
| 699 | ### Bandwidth Values |
| 700 | Typical modern systems: |
| 701 | - L1 cache: 200-500 GB/s (varies with frequency) |
| 702 | - L2 cache: 100-200 GB/s |
| 703 | - L3 cache: 50-100 GB/s |
| 704 | - Main memory: 20-100 GB/s (DDR4/DDR5, depends on channels) |
| 705 | |
| 706 | ### Latency Values |
| 707 | Typical modern systems: |
| 708 | - L1 cache: 1-2 ns |
| 709 | - L2 cache: 3-10 ns |
| 710 | - L3 cache: 10-40 ns (larger/3D V-Cache may be higher) |
| 711 | - Main memory: 25-50 ns (fast DDR5) to 60-120 ns (DDR4) |
| 712 | |
| 713 | ## Dependencies |
| 714 | |
| 715 | ### Build Requirements |
| 716 | |
| 717 | - **Required**: C11 compiler with OpenMP support (gcc or clang) |
| 718 | - **Recommended**: hwloc 2.x for portable cache topology detection |
| 719 | - **Optional**: libnuma for NUMA support (Linux only) |
| 720 | - **Optional**: libhugetlbfs for huge page size detection (Linux only) |
| 721 | |
| 722 | ### Runtime Requirements |
| 723 | |
| 724 | - **Required**: OpenMP runtime library (`libgomp1` on Debian/Ubuntu, `libgomp` on RHEL) |
| 725 | - **Optional**: libhwloc, libnuma, libhugetlbfs (same as build dependencies) |
| 726 | |
| 727 | ### Installing Dependencies |
| 728 | |
| 729 | ```bash |
| 730 | # Debian/Ubuntu - Build |
| 731 | apt-get install build-essential libhwloc-dev libnuma-dev libhugetlbfs-dev |
| 732 | |
| 733 | # Debian/Ubuntu - Runtime only (e.g., Docker images) |
| 734 | apt-get install libgomp1 libhwloc15 libnuma1 libhugetlbfs-dev |
| 735 | |
| 736 | # RHEL/CentOS/Fedora - Build |
| 737 | yum install gcc make hwloc-devel numactl-devel libhugetlbfs-devel |
| 738 | |
| 739 | # RHEL/CentOS/Fedora - Runtime only |
| 740 | yum install libgomp hwloc-libs numactl-libs libhugetlbfs |
| 741 | |
| 742 | # macOS (hwloc only, no NUMA) |
| 743 | brew install hwloc libomp |
| 744 | xcode-select --install |
| 745 | |
| 746 | # FreeBSD (hwloc 2 required, not hwloc 1) |
| 747 | pkg install gmake hwloc2 |
| 748 | ``` |
| 749 | |
| 750 | ### What Each Dependency Provides |
| 751 | |
| 752 | | Library | Purpose | Platforms | Build/Runtime | |
| 753 | |---------|---------|-----------|---------------| |
| 754 | | **libgomp** | OpenMP runtime (parallel execution) | All | Both | |
| 755 | | **hwloc 2** | Cache topology detection (L1/L2/L3 sizes) | Linux, macOS, BSD | Both | |
| 756 | | **libnuma** | NUMA-aware memory allocation | Linux only | Both | |
| 757 | | **libhugetlbfs** | Huge page size detection | Linux only | Both | |
| 758 | |
| 759 | **Note**: hwloc 2.x is required. hwloc 1.x uses a different API and is not supported. |
| 760 | |
| 761 | Without hwloc, the benchmark falls back to sysctl (macOS/BSD) or `/sys/devices/system/cpu/*/cache/` (Linux). |
| 762 | Without libnuma, memory is allocated without NUMA awareness (may underperform on multi-socket systems). |
| 763 | |
| 764 | ## License |
| 765 | |
| 766 | Mozilla Public License 2.0 |
| 767 | |
| 768 | ## See Also |
| 769 | |
| 770 | - [STREAM benchmark](https://www.cs.virginia.edu/stream/) |
| 771 | - [lmbench](https://sourceforge.net/projects/lmbench/) |
| 772 | - [ram_bench](https://github.com/emilk/ram_bench) |
| 773 |