Skip to content

Instantly share code, notes, and snippets.

@geniusnhu
Created August 29, 2021 09:10
Show Gist options
  • Save geniusnhu/3b5263cd933b2e17c9711a212a138f69 to your computer and use it in GitHub Desktop.
Save geniusnhu/3b5263cd933b2e17c9711a212a138f69 to your computer and use it in GitHub Desktop.
import numpy as np
import itertools
import sys
def append_matrix_with_itertools(X, Y):
""" Loop matrix using itertools.product()
"""
MTX = np.zeros((X, Y))
for i, j in itertools.product(range(X), range(Y)):
if (i%2==0) & (i%3==1):
MTX[i, j] = i**2/10
return MTX
def append_matrix_with_loop(X, Y):
""" Loop matrix using normal for loop
"""
MTX = np.zeros((X, Y))
for i in range(X):
for j in range(Y):
if (i%2==0) & (i%3==1):
MTX[i, j] = i**2/10
return MTX
>>> MTX_itertools = append_matrix_with_itertools(MTX.shape[0], MTX.shape[1])
>>> MTX_loop = append_matrix_with_loop(MTX.shape[0], MTX.shape[1])
### Matrix size
>>> print(sys.getsizeof(MTX_itertools)/ (1024 * 1024))
>>> print(sys.getsizeof(MTX_loop)/ (1024 * 1024))
7.6295013427734375
7.6295013427734375
### Run time
>>> timeit(append_matrix_with_itertools(1000, 1000))
1 loop, best of 5: 234 ms per loop
>>> timeit(append_matrix_with_loop(1000, 1000))
1 loop, best of 5: 347 ms per loop
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment