Skip to content

Instantly share code, notes, and snippets.

@c-wei
Created October 2, 2024 01:10
Show Gist options
  • Save c-wei/625dcf09f2801c0e6a5c852f00aa65f5 to your computer and use it in GitHub Desktop.
Save c-wei/625dcf09f2801c0e6a5c852f00aa65f5 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
import numpy as np
def read_matrix(N):
matrix = []
for _ in range(N):
row = list(map(int, input().split()))
matrix.append(row)
return matrix
def multiply_matrices(A, B, N):
result = [[0] * N for _ in range(N)]
# Adjust block size as necessary to be cache-friendly
block_size = int(1 + N / 4)
# Perform matrix multiplication block-by-block
for i in range(0, N, block_size):
for j in range(0, N, block_size):
for k in range(0, N, block_size):
# Mini matrix multiplication within block
for i1 in range(i, min(i + block_size, N)):
for j1 in range(j, min(j + block_size, N)):
for k1 in range(k, min(k + block_size, N)):
result[i1][j1] += A[i1][k1] * B[k1][j1]
np_result = np.array(result)
formatted_result = format_array(np_result)
return formatted_result
def format_array(arr): return np.array2string(arr).replace('[[','').replace(' [','').replace(']','')
if __name__ == "__main__":
N = int(input().strip())
matrix_A = read_matrix(N)
matrix_B = read_matrix(N)
result_matrix = multiply_matrices(matrix_A, matrix_B, N)
print(result_matrix)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment