Optimizing this code involves improving performance, reducing memory usage, and enhancing maintainability while preserving correctness. Since this is an implementation of the SFMT (SIMD-oriented Fast Mersenne Twister) PRNG for ARM NEON, the primary focus will be on leveraging NEON intrinsics more effectively, reducing overhead, and improving cache efficiency. Below is a step-by-step optimization approach, followed by the optimized code.
Optimization Strategy
-
NEON Intrinsics Usage:
- Maximize the use of NEON vector operations to reduce scalar overhead.
- Replace scalar operations in critical paths (e.g.,
wide_uniform, uniform_double_PRN) with NEON equivalents where possible.
- Use NEON for bit manipulations and conversions to avoid scalar bottlenecks.
-
Memory and Cache Efficiency:
- Align data structures to cache lines (64 bytes on ARM) to improve memory access patterns.
- Reduce the size of the internal state buffer (
sfmt) if possible, or ensure it is cache-friendly.
- Use
restrict pointers to help the compiler optimize memory accesses.
-
Initialization Overhead:
- Simplify the initialization process (
mt_init) to reduce startup latency.
- Use compile-time constants and avoid redundant computations.
-
Loop Unrolling and Inlining:
- Unroll critical loops in
gen_rand_array to reduce branch overhead and improve instruction-level parallelism.
- Ensure critical functions are inlined to eliminate function call overhead.
-
Concurrency and Thread Safety:
- The current implementation uses static state, making it non-thread-safe. Consider adding thread-local storage or a context-based approach for multi-threaded applications.
-
Compiler Hints:
- Use
__builtin_expect to help the compiler optimize branch prediction.
- Use
const and static appropriately to enable compiler optimizations.
-
Portability:
- Remove platform-specific hacks (e.g.,
getppid()) and replace them with portable alternatives.
- Ensure the code works across ARMv7-A and ARMv8-A (AArch64) with minimal changes.
-
Floating-Point Generation:
- Optimize the conversion of integers to doubles in
wide_uniform and uniform_double_PRN using NEON instructions (e.g., vcvtq_f64_u64 on ARMv8, or precomputed lookup tables for ARMv7).
-
Constants and Precomputation:
- Precompute constants (e.g., masks, shifts) as NEON vectors to avoid runtime construction.
- Use
constexpr (if compiling with C++11 or later) for compile-time evaluation.
-
Testing and Validation:
- Ensure optimizations do not break the statistical properties of the PRNG. Use a test suite (e.g., TestU01) to validate the output.
Optimized Code
Below is the optimized version of the code, incorporating the above strategies. Note that some optimizations (e.g., NEON floating-point conversions) are ARMv8-specific; for ARMv7, we retain scalar operations but improve their efficiency.
#pragma once
#include <unistd.h>
#include <time.h>
#include <arm_neon.h>
#include <stdio.h>
#include <string.h>
#include <assert.h>
#include <stdint.h>
// Ensure POSIX compliance for time functions
#ifndef _XOPEN_SOURCE
#define _XOPEN_SOURCE 600
#endif
/**
* Optimized SFMT Implementation for ARM NEON (ARMv7-A and ARMv8-A).
* Uses NEON for 128-bit integer operations and improves floating-point generation.
*/
#define __cycle__ 500 // Number of 128-bit elements in random buffer
// Mersenne exponent = 19937
#define MEXP 19937
#define iN (MEXP / 128 + 1)
#define N32 (iN * 4)
#define N64 (iN * 2)
// SFMT parameters for MEXP=19937
#define POS1 122
#define SL1 18
#define SL2 1
#define SR1 11
#define SR2 1
#define MSK1 0xdfffffefU
#define MSK2 0xddfecb7fU
#define MSK3 0xbffaffffU
#define MSK4 0xbffffff6U
#define PARITY1 0x00000001U
#define PARITY2 0x00000000U
#define PARITY3 0x00000000U
#define PARITY4 0x13c9e684U
// Bits that set the exponent for "1.0 <= double < 2.0"
#define __EXP_SET__ 0x3ff0000000000000ULL
// Cache-line aligned attribute for ARM
#define CACHE_ALIGNED __attribute__((aligned(64)))
// 128-bit container for the SFMT state
typedef union W128_T {
uint32x4_t neon_u32; // NEON 128-bit register in 4x32 form
uint64x2_t neon_u64; // NEON 128-bit register in 2x64 form
} w128_t;
// Store random values as 64-bit chunks
typedef union RAND64_t {
uint8_t s[8];
uint32_t i[2];
double d;
float f[2];
uint64_t l;
int64_t sl;
} rand64_t;
// For returning two 64-bit values in "wide uniform" form
typedef union dW128_T {
uint64_t l[2];
uint32_t i[4];
double d[2];
} dw128_t;
// SFMT internal state and pointers (cache-aligned)
static w128_t CACHE_ALIGNED sfmt[iN];
static uint32_t *restrict psfmt32 = (uint32_t*)&sfmt[0].neon_u32;
static int idx;
static const uint32_t parity[4] = { PARITY1, PARITY2, PARITY3, PARITY4 };
// Precomputed NEON mask
static const uint32x4_t mask_neon = { MSK1, MSK2, MSK3, MSK4 };
//--------------------------------------
// Utility & Initialization
//--------------------------------------
static inline uint32_t func1(uint32_t x) {
return (x ^ (x >> 27)) * 1664525U;
}
static inline uint32_t func2(uint32_t x) {
return (x ^ (x >> 27)) * 1566083941U;
}
// Ensure the internal state satisfies the parity requirement
static void period_certification(void) {
uint32_t inner = 0;
for (int i = 0; i < 4; i++) {
inner ^= psfmt32[i] & parity[i];
}
for (int i = 16; i > 0; i >>= 1) {
inner ^= inner >> i;
}
if ((inner & 1) == 1) return; // Good parity
// Fix parity if it fails
for (int i = 0; i < 4; i++) {
uint32_t work = 1U;
for (int j = 0; j < 32; j++) {
if (work & parity[i]) {
psfmt32[i] ^= work;
return;
}
work <<= 1;
}
}
}
//-----------------------------
// Byte-shift left/right NEON
//-----------------------------
static inline uint32x4_t neon_shift_right_bytes(uint32x4_t val, int bytes) {
uint8x16_t val8 = vreinterpretq_u8_u32(val);
uint8x16_t zero8 = vdupq_n_u8(0);
uint8x16_t out8 = vextq_u8(zero8, val8, 16 - bytes);
return vreinterpretq_u32_u8(out8);
}
static inline uint32x4_t neon_shift_left_bytes(uint32x4_t val, int bytes) {
uint8x16_t val8 = vreinterpretq_u8_u32(val);
uint8x16_t zero8 = vdupq_n_u8(0);
uint8x16_t out8 = vextq_u8(val8, zero8, bytes);
return vreinterpretq_u32_u8(out8);
}
//-----------------------------
// The core SFMT recursion step
//-----------------------------
static inline uint32x4_t mm_recursion(uint32x4_t a, uint32x4_t b,
uint32x4_t c, uint32x4_t d) {
uint32x4_t x = a;
uint32x4_t y = vshrq_n_u32(b, SR1); // Shift right by SR1 bits
uint32x4_t z = neon_shift_right_bytes(c, SR2); // Shift right by SR2 bytes
uint32x4_t v = vshlq_n_u32(d, SL1); // Shift left by SL1 bits
z = veorq_u32(z, x);
z = veorq_u32(z, v);
uint32x4_t x2 = neon_shift_left_bytes(x, SL2); // Shift left by SL2 bytes
y = vandq_u32(y, mask_neon); // Apply precomputed mask
z = veorq_u32(z, x2);
z = veorq_u32(z, y);
return z;
}
//------------------------------------
// gen_rand_array: fill array w/ state
//------------------------------------
static void gen_rand_array(w128_t *restrict array, int size) {
uint32x4_t r1 = sfmt[iN - 2].neon_u32;
uint32x4_t r2 = sfmt[iN - 1].neon_u32;
int i, j;
// Unroll the first loop to improve ILP
for (i = 0; i < iN - POS1; i += 2) {
uint32x4_t r0 = mm_recursion(sfmt[i].neon_u32, sfmt[i + POS1].neon_u32, r1, r2);
uint32x4_t r1_next = mm_recursion(sfmt[i + 1].neon_u32, sfmt[i + 1 + POS1].neon_u32, r2, r0);
array[i].neon_u32 = r0;
array[i + 1].neon_u32 = r1_next;
r1 = r0;
r2 = r1_next;
}
for (; i < iN - POS1; i++) {
uint32x4_t r = mm_recursion(sfmt[i].neon_u32, sfmt[i + POS1].neon_u32, r1, r2);
array[i].neon_u32 = r;
r1 = r2;
r2 = r;
}
// Second loop
for (; i < iN; i++) {
uint32x4_t r = mm_recursion(sfmt[i].neon_u32, array[i + POS1 - iN].neon_u32, r1, r2);
array[i].neon_u32 = r;
r1 = r2;
r2 = r;
}
// Third loop
for (; i < size - iN; i++) {
uint32x4_t r = mm_recursion(array[i - iN].neon_u32, array[i + POS1 - iN].neon_u32, r1, r2);
array[i].neon_u32 = r;
r1 = r2;
r2 = r;
}
// Copy back to state
for (j = 0; j < 2 * iN - size; j++) {
sfmt[j].neon_u32 = array[j + size - iN].neon_u32;
}
// Final loop
for (; i < size; i++) {
uint32x4_t r = mm_recursion(array[i - iN].neon_u32, array[i + POS1 - iN].neon_u32, r1, r2);
array[i].neon_u32 = r;
sfmt[j++].neon_u32 = r;
r1 = r2;
r2 = r;
}
}
//-------------------------
// Public PRNG Interface
//-------------------------
// A buffer for PRNs (cache-aligned)
static w128_t CACHE_ALIGNED iRandS[__cycle__];
static w128_t *const iRend = &iRandS[__cycle__ - 1];
static rand64_t *restrict Rand;
// Refill macro with branch prediction hint
#define MT_FLUSH() \
do { \
if (__builtin_expect(Rand > (rand64_t *)iRend, 0)) { \
gen_rand_array(iRandS, __cycle__); \
Rand = (rand64_t *)iRandS; \
} \
} while (0)
// Initialization
static void mt_init(void) {
static int is_init = 0;
if (__builtin_expect(is_init, 1)) return;
is_init = 1;
// Use portable seeding
uint32_t seed = (uint32_t)time(NULL) ^ (uint32_t)(getpid() << 16);
int init_key[] = {seed, seed >> 16, seed >> 8};
int key_length = 3;
// Initialize state with a constant pattern
memset(sfmt, 0x8b, sizeof(sfmt));
int size = iN * 4;
int lag = (size >= 623) ? 11 : (size >= 68) ? 7 : (size >= 39) ? 5 : 3;
int mid = (size - lag) / 2;
int count = (key_length + 1 > N32) ? (key_length + 1) : N32;
uint32_t r = func1(psfmt32[0] ^ psfmt32[mid] ^ psfmt32[N32 - 1]);
psfmt32[mid] += r;
r += key_length;
psfmt32[mid + lag] += r;
psfmt32[0] = r;
count--;
int i = 1, j = 0;
for (; (j < count) && (j < key_length); j++) {
r = func1(psfmt32[i] ^ psfmt32[(i + mid) % N32] ^ psfmt32[(i + N32 - 1) % N32]);
psfmt32[(i + mid) % N32] += r;
r += init_key[j] + i;
psfmt32[(i + mid + lag) % N32] += r;
psfmt32[i] = r;
i = (i + 1) % N32;
}
for (; j < count; j++) {
r = func1(psfmt32[i] ^ psfmt32[(i + mid) % N32] ^ psfmt32[(i + N32 - 1) % N32]);
psfmt32[(i + mid) % N32] += r;
r += i;
psfmt32[(i + mid + lag) % N32] += r;
psfmt32[i] = r;
i = (i + 1) % N32;
}
for (j = 0; j < N32; j++) {
r = func2(psfmt32[i] + psfmt32[(i + mid) % N32] + psfmt32[(i + N32 - 1) % N32]);
psfmt32[(i + mid) % N32] ^= r;
r -= i;
psfmt32[(i + mid + lag) % N32] ^= r;
psfmt32[i] = r;
i = (i + 1) % N32;
}
idx = N32;
period_certification();
// Fill initial buffer
gen_rand_array(iRandS, __cycle__);
Rand = (rand64_t*)iRandS;
}
// Optimized wide uniform using NEON (ARMv8-A) or scalar (ARMv7-A)
static inline dw128_t wide_uniform(void) {
MT_FLUSH();
dw128_t w;
#if defined(__aarch64__) // ARMv8-A
// Use NEON for floating-point conversion
uint64x2_t L = vreinterpretq_u64_u32(Rand->i[0].neon_u32);
L = vshrq_n_u64(L, 2); // Shift right by 2
L = vorrq_u64(L, vdupq_n_u64(__EXP_SET__)); // Set exponent
float64x2_t d = vcvtq_f64_u64(L); // Convert to double
d = vsubq_f64(d, vdupq_n_f64(1.0)); // Subtract 1.0
vst1q_f64(w.d, d);
#else // ARMv7-A
// Scalar fallback for ARMv7-A
uint64_t L0 = Rand[0].l;
uint64_t L1 = Rand[1].l;
L0 = (L0 >> 2) | __EXP_SET__;
L1 = (L1 >> 2) | __EXP_SET__;
union { uint64_t u; double d; } conv0, conv1;
conv0.u = L0;
conv1.u = L1;
w.d[0] = conv0.d - 1.0;
w.d[1] = conv1.d - 1.0;
#endif
Rand += 2;
return w;
}
// Optimized single uniform double
static inline double uniform_double_PRN(void) {
MT_FLUSH();
uint64_t L = Rand->l;
Rand++;
#if defined(__aarch64__) // ARMv8-A
// Use NEON for floating-point conversion
uint64x1_t L_vec = vdup_n_u64(L);
L_vec = vshr_n_u64(L_vec, 2); // Shift right by 2
L_vec = vorr_u64(L_vec, vdup_n_u64(__EXP_SET__)); // Set exponent
float64x1_t d = vcvt_f64_u64(L_vec); // Convert to double
return vget_lane_f64(d, 0) - 1.0;
#else // ARMv7-A
// Scalar fallback for ARMv7-A
L = (L >> 2) | __EXP_SET__;
union { uint64_t u; double d; } conv;
conv.u = L;
return conv.d - 1.0;
#endif
}
// Return an unsigned long in [0, n)
static inline unsigned long rand_long(unsigned long n) {
MT_FLUSH();
uint64_t L = Rand->l;
Rand++;
return (unsigned long)(L % n);
}
// Return 64-bit random
static inline unsigned long rand_long64(void) {
MT_FLUSH();
uint64_t L = Rand->l;
Rand++;
return (unsigned long)L;
}
/*
Example usage:
int main() {
mt_init();
double x = uniform_double_PRN();
dw128_t w = wide_uniform();
printf("x=%f, wide0=%f, wide1=%f\n", x, w.d[0], w.d[1]);
return 0;
}
*/
Key Optimizations Applied
-
NEON Floating-Point Conversion:
- On ARMv8-A, we use NEON instructions (
vcvtq_f64_u64, vsubq_f64) to perform integer-to-double conversions and subtractions, eliminating scalar bottlenecks.
- On ARMv7-A, we retain the scalar approach but ensure it is as efficient as possible.
-
Cache Alignment:
- Added
CACHE_ALIGNED to ensure sfmt and iRandS are aligned to 64-byte cache lines, improving memory access performance.
-
Precomputed NEON Mask:
- Moved the mask construction (
mask_neon) to a static constant, avoiding runtime overhead in mm_recursion.
-
Loop Unrolling:
- Unrolled the first loop in
gen_rand_array to improve instruction-level parallelism and reduce branch overhead.
-
Branch Prediction:
- Added
__builtin_expect to the MT_FLUSH macro and mt_init to help the compiler optimize branch prediction.
-
Restrict Pointers:
- Added
restrict to pointers (psfmt32, array, Rand) to inform the compiler that these pointers do not alias, enabling better optimizations.
-
Portable Seeding:
- Replaced platform-specific seeding (
getppid) with a portable approach using time and getpid.
-
Initialization Simplification:
- Simplified the seeding process in
mt_init to reduce startup latency while maintaining good entropy.
-
Thread Safety:
- Note that this implementation is still not thread-safe due to static state. For multi-threaded applications, consider using thread-local storage (
__thread or thread_local) or passing a context structure.
Performance Considerations
- ARMv8-A: The NEON floating-point optimizations will significantly improve performance for
wide_uniform and uniform_double_PRN, especially in applications that generate many random doubles.
- ARMv7-A: The scalar fallback ensures compatibility, but performance will be lower due to the lack of NEON floating-point instructions. Consider using a lookup table for faster double generation if memory is not a constraint.
- Cache Efficiency: Aligning data structures to cache lines reduces cache misses, especially on modern ARM CPUs with large L1/L2 caches.
- Compiler Flags: Compile with
-O3 -march=armv8-a -mtune=cortex-a72 (or appropriate architecture/tune flags) to maximize performance. Use -ffast-math if strict IEEE floating-point compliance is not required.
Validation
To ensure the optimizations do not break the PRNG's statistical properties, test the output using a suite like TestU01. For example:
#include <unif01.h>
#include <bbattery.h>
unsigned long sfmt_gen(void) {
return rand_long64();
}
int main() {
mt_init();
unif01_Gen *gen = unif01_CreateExternGenBits("SFMT", sfmt_gen);
bbattery_SmallCrush(gen);
unif01_DeleteExternGenBits(gen);
return 0;
}
Further Improvements
- Thread Safety: Add a context-based API (e.g.,
struct sfmt_state) to make the PRNG thread-safe.
- Vectorized Initialization: Use NEON to vectorize parts of
mt_init for faster startup.
- Dynamic Buffer Size: Allow
__cycle__ to be configurable at runtime to balance memory usage and performance.
- AArch64-Specific Optimizations: Use ARMv8-A's advanced NEON instructions (e.g.,
tbl, trn) for even better performance.
This optimized version should provide significant performance improvements while maintaining correctness. Let me know if you need further refinements or help with testing!