In [1]:
def mul1(n):
return array([[(i + 1) * (j + 1) for i in xrange(n)] for j in xrange(n)])
In [2]:
mul1(4)
Out[2]:
In [3]:
timeit mul1(100)
In [4]:
def mul2(n):
M = arange(1, n + 1).reshape((-1, 1))
M = tile(M, (1, n))
N = arange(1, n + 1).reshape((1, -1))
N = tile(N, (n, 1))
return M * N
In [5]:
mul2(4)
Out[5]:
In [6]:
timeit mul2(100)
Using NumPy is about 20 times faster here.
In [7]:
def mul3(n):
M = arange(1, n + 1).reshape((-1, 1))
N = arange(1, n + 1).reshape((1, -1))
return M * N
In [8]:
mul3(4)
Out[8]:
In [9]:
timeit mul3(100)
This optimized version is about 60 times faster than the original Python version.