Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 48 additions & 2 deletions src/linal_vector.c
Original file line number Diff line number Diff line change
Expand Up @@ -162,7 +162,11 @@ vec_add(const Vector a, const Vector b, Vector *result)

/**
* @brief Subtract two vectors element-wise.
*
* Uses OpenMP parallel + SIMD for large vectors (2 threads to limit
* memory bandwidth pressure) and omp simd for the serial path.
*/
__attribute__((optimize("O3")))
int
vec_sub(const Vector a, const Vector b, Vector *result)
{
Expand All @@ -178,8 +182,50 @@ vec_sub(const Vector a, const Vector b, Vector *result)
return -1;
}

for (size_t i = 0; i < a.size; i++) {
result->data[i] = a.data[i] - b.data[i];
size_t count = a.size;

#if defined(_OPENMP)
/* 2 threads — balances parallelism with memory bandwidth for 3-array access */
if (count >= 262144) {
const double *A = a.data;
const double *B = b.data;
double *R = result->data;
/* Process in 112K blocks for cache-friendly static scheduling */
size_t block_size = 114688;
size_t full_blocks = count / block_size;
size_t tail_start = full_blocks * block_size;
#pragma omp parallel for num_threads(2) schedule(static, 2)
for (size_t block = 0; block < full_blocks; block++) {
size_t start = block * block_size;
/* Prefetch next 2 blocks for deeper lookahead */
size_t pf1 = start + block_size;
size_t pf2 = start + 2 * block_size;
__builtin_prefetch(&A[pf1], 0, 3);
__builtin_prefetch(&B[pf1], 0, 3);
__builtin_prefetch(&R[pf1], 1, 3);
if (pf2 < count) {
__builtin_prefetch(&A[pf2], 0, 1);
__builtin_prefetch(&B[pf2], 0, 1);
__builtin_prefetch(&R[pf2], 1, 1);
}
#pragma omp simd safelen(2) aligned(A:32) aligned(B:32) aligned(R:32)
for (size_t i = start; i < start + block_size; i++) {
R[i] = A[i] - B[i];
}
}
/* Tail without prefetch */
#pragma omp simd safelen(2) aligned(A:16) aligned(B:16) aligned(R:16)
for (size_t i = tail_start; i < count; i++) {
R[i] = A[i] - B[i];
}
} else
#endif
{
/* Serial SIMD path */
#pragma omp simd safelen(2)
for (size_t i = 0; i < count; i++) {
result->data[i] = a.data[i] - b.data[i];
}
}

return 0;
Expand Down
138 changes: 138 additions & 0 deletions tests/benchmark_vec_sub.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
/*
* @file benchmark_vec_sub.c
* @brief Benchmark vec_sub across vector sizes with correctness validation.
*
* Uses CLOCK_MONOTONIC_RAW for nanosecond precision.
* Runs multiple repeats per size and reports median to reduce noise.
*/

#include "linal.h"
#include <math.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <time.h>

#define REPEATS 20
#define EPSILON 1e-6

static const size_t sizes[] = {
65536, 262144, 1048576, 4194304, 16777216, 67108864
};
static const int n_sizes = sizeof(sizes) / sizeof(sizes[0]);

static void fill_vector(Vector *v, uint64_t seed)
{
double *d = v->data;
uint64_t state = seed;
for (size_t i = 0; i < v->size; i++) {
state = state * 6364136223846793005ULL + 1442695040888963407ULL;
d[i] = (double)((state >> 11) & 0x3FFFFF) / (double)(1 << 21) - 1.0;
}
}

static double
median_double(double *arr, int n)
{
/* Simple insertion sort for small n */
for (int i = 1; i < n; i++) {
double key = arr[i];
int j = i - 1;
while (j >= 0 && arr[j] > key) {
arr[j + 1] = arr[j];
j--;
}
arr[j + 1] = key;
}
if (n % 2 == 0)
return (arr[n / 2 - 1] + arr[n / 2]) / 2.0;
return arr[n / 2];
}

static bool
validate(const Vector *a, const Vector *b, const Vector *result)
{
for (size_t i = 0; i < a->size; i++) {
double expected = a->data[i] - b->data[i];
if (fabs(result->data[i] - expected) > EPSILON) {
return false;
}
}
return true;
}

int main(void)
{
bool all_valid = true;
double primary_us = 0.0;

printf("=== vec_sub benchmark (median of %d runs) ===\n", REPEATS);
printf("%-12s %12s %10s\n", "Size", "Time(us)", "Valid");

double times[REPEATS];

for (int s = 0; s < n_sizes; s++) {
size_t dim = sizes[s];

Vector a = vec_create(dim);
Vector b = vec_create(dim);
Vector result = vec_create(dim);

if (!a.data || !b.data || !result.data) {
printf("FAIL allocation %zu\n", dim);
all_valid = false;
continue;
}

fill_vector(&a, 42 + s * 7);
fill_vector(&b, 99 + s * 13);

/* Correctness check */
int rc = vec_sub(a, b, &result);
bool valid = (rc == 0) && validate(&a, &b, &result);

if (!valid) {
printf("FAIL %zu: validation error (rc=%d)\n", dim, rc);
all_valid = false;
continue;
}

/* Warmup */
vec_sub(a, b, &result);
vec_sub(a, b, &result);
vec_sub(a, b, &result);

/* Timed runs */
for (int r = 0; r < REPEATS; r++) {
struct timespec ts, te;
clock_gettime(CLOCK_MONOTONIC_RAW, &ts);
vec_sub(a, b, &result);
clock_gettime(CLOCK_MONOTONIC_RAW, &te);

double ns = (double)(te.tv_sec - ts.tv_sec) * 1e9
+ (double)(te.tv_nsec - ts.tv_nsec);
times[r] = ns / 1000.0; /* Convert to µs */
}

double median_us = median_double(times, REPEATS);

if (s == n_sizes - 1)
primary_us = median_us;

printf("%12zu %12.3f %5s\n", dim, median_us, "OK");

vec_free(&a);
vec_free(&b);
vec_free(&result);
}

printf("\n=== Correctness: %s ===\n", all_valid ? "PASS" : "FAIL");

if (all_valid)
printf("METRIC total_us=%.3f\n", primary_us);
else
printf("METRIC total_us=999999.000\n");

return EXIT_SUCCESS;
}
7 changes: 7 additions & 0 deletions tests/meson.build
Original file line number Diff line number Diff line change
Expand Up @@ -154,6 +154,13 @@ benchmark_vec_add = executable(
include_directories: [public_headers, generated_headers],
)

benchmark_vec_sub = executable(
'benchmark_vec_sub',
files('benchmark_vec_sub.c'),
dependencies: [linal_dep],
include_directories: [public_headers, generated_headers],
)

# Run all tests
test('mat_create', test_mat_create)
test('mat_memory', test_mat_memory)
Expand Down
Loading