Top Python Libraries

Top Python Libraries

Share this post

Top Python Libraries
Top Python Libraries
12 Ways to Boost Data Science Matrix Ops: Numpy to Cython

12 Ways to Boost Data Science Matrix Ops: Numpy to Cython

Python Matrix Ops: Faster, Further, Better

Meng Li's avatar
Meng Li
Jun 11, 2024
∙ Paid

Share this post

Top Python Libraries
Top Python Libraries
12 Ways to Boost Data Science Matrix Ops: Numpy to Cython
Share
Photo by Bryanquille on Pixabay

Lately, I’ve been using Python for scientific computing, but I’m bothered by its slow speed.

Matrix calculations are also sluggish. Let me share some tips to speed things up.

You can accelerate in two ways: through high-level API and low-level API.

Low-Level API

Photo by Olivier Collet on Unsplash

The simplest and crudest way is to directly traverse with a triple loop:

def matrix_multiplication_loop(A, B):
    m = A.shape[0]
    n = A.shape[1]
    l = B.shape[1]
    C = np.zeros([m, l])
    for i in range(m):
        for j in range(l):
            for k in range(n):
                C[i][j] += A[i][k] * B[k][j]  # Accumulate the result of each multiplication
    return C
A = np.random.random([300, 12])
B = np.random.random([12, 256])
%timeit C = matrix_multiplication_loop(A, B)
1 loop, best of 3: 2.22 s per loop

This post is for paid subscribers

Already a paid subscriber? Sign in
© 2025 Meng Li
Privacy ∙ Terms ∙ Collection notice
Start writingGet the app
Substack is the home for great culture

Share