Skip to content

Instantly share code, notes, and snippets.

@minoki
Created January 27, 2021 11:51
Show Gist options
  • Save minoki/d2be9e3207b9e1c5b19848cbac7aec45 to your computer and use it in GitHub Desktop.
Save minoki/d2be9e3207b9e1c5b19848cbac7aec45 to your computer and use it in GitHub Desktop.
BLASなんもわからん
#include <cblas_openblas.h>
#include <stdio.h>
#include <math.h>
int main(void)
{
double A[3][3] = {
{1.0, 2.0, 3.0},
{2.0, 3.0, 4.0},
{4.0, 5.0, 6.0},
};
double B[3][4] = {
{1.0, 2.0, 3.0, 2.0},
{2.0, -2.0, 4.0, 0.0},
{1.0, 5.0, 6.0, -1.0},
};
double C[3][4];
printf("A: {");
for (size_t i = 0; i < 3 * 3; ++i) {
printf("%g, ", (&A[0][0])[i]);
}
puts("}");
for (size_t i = 0; i < 3; ++i) {
for (size_t j = 0; j < 3; ++j) {
printf("%g, ", A[i][j]); // 3 * i + j
}
puts("");
}
puts("---");
printf("sizeof(B[0]) = %zu\n", sizeof(B[0]));
printf("B: {");
for (size_t i = 0; i < 3 * 4; ++i) {
printf("%g, ", (&B[0][0])[i]);
}
puts("}");
for (size_t j = 0; j < 3; ++j) {
for (size_t k = 0; k < 4; ++k) {
printf("%g, ", B[j][k]); // 4 * j + k
}
puts("");
}
puts("---");
for (size_t i = 0; i < 3; ++i) {
for (size_t k = 0; k < 4; ++k) {
double x = 0.0;
for (size_t j = 0; j < 3; ++j) {
x += A[i][j] * B[j][k];
}
C[i][k] = x;
}
}
printf("C (naive): {");
for (size_t i = 0; i < 3 * 4; ++i) {
printf("%g, ", (&C[0][0])[i]);
}
puts("}");
for (size_t i = 0; i < 3; ++i) {
for (size_t k = 0; k < 4; ++k) {
printf("%g, ", C[i][k]); // 4 * i + k
}
puts("");
}
puts("---");
for (size_t i = 0; i < 3; ++i) {
for (size_t k = 0; k < 4; ++k) {
C[i][k] = NAN;
}
}
cblas_dgemm(CblasRowMajor /* or CblasColMajor */, CblasNoTrans, CblasNoTrans, /* m */ 3, /* n */ 4, /* k */ 3, /* alpha */ 1.0, &A[0][0], /* lda */ 3, &B[0][0], /* ldb */ 4, /* beta */ 0.0, &C[0][0], /* ldc */ 4);
printf("C (blas): {");
for (size_t i = 0; i < 3 * 4; ++i) {
printf("%g, ", (&C[0][0])[i]);
}
puts("}");
for (size_t i = 0; i < 3; ++i) {
for (size_t k = 0; k < 4; ++k) {
printf("%g, ", C[i][k]); // 4 * i + k
}
puts("");
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment