Skip to content

Instantly share code, notes, and snippets.

@eginez
Created June 16, 2024 23:18
Show Gist options
  • Save eginez/c068bbebe740af9a7270c1afd599f2be to your computer and use it in GitHub Desktop.
Save eginez/c068bbebe740af9a7270c1afd599f2be to your computer and use it in GitHub Desktop.
Mat multiplication
// gcc -O3 one.c && ./a.out
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
float rand_float() { return (float)rand() / (float)RAND_MAX; }
float *calcmatrix(float ***matrix, int **indices, int big_size) {
float acc = 1;
int i_loc, j_loc;
float *res = (float *)malloc(big_size * sizeof(float));
for (int i = 0; i < big_size; i++) {
for (int j = 0; j < big_size; j++) {
acc = 1;
for (int z = 0; z < 32; z++) {
i_loc = indices[z][i];
j_loc = indices[z][j];
// i_loc = 4;
// j_loc = 5;
acc *= matrix[z][i_loc][j_loc];
}
res[i] += acc;
}
}
return res;
}
int main() {
// create 3 dimension big matrix
// 32, 16x16 matrices
srand(time(0));
int s, x, y;
s = 32;
x = y = 16;
int ind_size = 10000;
float ***mat = (float ***)malloc(s * sizeof(float **));
for (int i = 0; i < s; i++) {
mat[i] = (float **)malloc(x * sizeof(float *));
for (int j = 0; j < x; j++) {
mat[i][j] = (float *)malloc(y * sizeof(float));
}
}
// Fill in matrix with random numbers
for (int k = 0; k < s; k++) {
for (int i = 0; i < x; i++) {
for (int j = 0; j < y; j++) {
mat[k][i][j] = rand_float();
}
}
}
int **indices = (int **)malloc(s * sizeof(int *));
for (int k = 0; k < s; k++) {
indices[k] = (int *)malloc(ind_size * sizeof(int));
}
// Fill in matrix with numbers from 0 to x
for (int i = 0; i < s; i++) {
for (int j = 0; j < ind_size; j++) {
indices[i][j] = rand() % x;
}
}
clock_t start_time = clock();
float *val = calcmatrix(mat, indices, ind_size);
clock_t end_time = clock();
double time_taken = (double)(end_time - start_time) / CLOCKS_PER_SEC;
//
// Print the time taken to print the matrix
printf("Time taken to calc the matrix: %f seconds\n", time_taken);
// printf("val %s\n", val);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment