Skip to content

Instantly share code, notes, and snippets.

@gdetor
Created February 7, 2023 00:26
Show Gist options
  • Save gdetor/57827f497ad4230fce76509b3a2963b0 to your computer and use it in GitHub Desktop.
Save gdetor/57827f497ad4230fce76509b3a2963b0 to your computer and use it in GitHub Desktop.
Example of POSIX memalign in C
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 1000000
typedef struct {
float *x;
} test_s;
void add(float * restrict a, float * restrict b, float * restrict c)
{
size_t i;
for (i = 0; i < SIZE; ++i) {
c[i] = a[i] + b[i];
}
}
int main()
{
clock_t t0, tf;
float *a = NULL, *b = NULL;
float *Aa = NULL, *Ab = NULL;
test_s *C, *AC;
a = (float *)malloc(sizeof(float) * SIZE);
b = (float *)malloc(sizeof(float) * SIZE);
C = (test_s *)malloc(sizeof(test_s));
C->x = (float *)malloc(SIZE * sizeof(float));
posix_memalign((void *)&Aa, 128, SIZE * sizeof(float));
posix_memalign((void *)&Ab, 128, SIZE * sizeof(float));
posix_memalign((void *)&AC, 128, sizeof(test_s));
posix_memalign((void *)&AC->x, 128, SIZE * sizeof(float));
t0 = clock();
add(a, b, C->x);
tf = clock();
printf("Non-aligned array: %lf\n", ((double)(tf - t0) / CLOCKS_PER_SEC));
t0 = clock();
add(Aa, Ab, AC->x);
tf = clock();
printf("Aligned array: %lf\n", ((double)(tf - t0) / CLOCKS_PER_SEC));
free(a);
free(b);
free(Aa);
free(Ab);
free(C->x);
free(C);
free(AC->x);
free(AC);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment