2

I am experimenting with the time that it takes to multiply matrices using numpy arrays. The following code uses the time and numpy modules. I have created some time variables (t0, t1, t2, t3) to keep track of the time that passes between specific moments of the code.

t0 is the initial instant of running the code.

t1 is how much time has elapsed after creating 2 matrices of specific dimensions of int numbers (defined by variables a and b).

t2 is how much time it takes to multiply the 2 matrices of int numbers.

t3 is how much time it takes to create and multiply 2 matrices of specific dimensions of float numbers.

Shockingly, for a=1500, and b=1500, it takes 7.41 seconds to run the int matrices multiplications, and only 0.39 seconds to run the float matrices multiplication.

As far as I know, floats take more memory that ints, so....what is going on here, should be the other way around? Shouldn't it be faster to multiply int numbers?

I have used the following code:

import numpy as np
import time as t

a = 1500
b = 1500

t0=t.time()

x1 = np.random.random((a, b))
x2 = np.random.random((b, a))

x1 = np.around(x1)
x2 = np.around(x2)

x1 = x1.astype(int)
x2 = x2.astype(int)

t1 = t.time() - t0
print("t1 = ",t1)

x3 = x1.dot(x2)

t2 = t.time() - (t1 + t0)
print("t2 = ",t2)

y1 = np.random.random((a, b))
y2 = np.random.random((b, a))

y3 = y1.dot(y2)

t3 = t.time() - (t2 + t0)
print("t3 = ",t3)

And this is the result you get when you run the code:

t1 =  0.2694694995880127
t2 =  7.419719934463501
t3 =  0.3991219997406006
Arman Mojaver
  • 352
  • 1
  • 9
  • 1
    Have a look here: https://stackoverflow.com/questions/19839539/how-to-get-faster-code-than-numpy-dot-for-matrix-multiplication – Paddy Harrison Apr 02 '20 at 14:35
  • In `numpy` the default dtypes are `np.float64` and `np.int64`, both 64 bits (default size on most modern machines). Element-wise multiplication `a*b` is basically the same speed for both. But `np.dot` (matrix multiplication) uses BLAS (or similar packages) for floats. – hpaulj Apr 02 '20 at 17:22
  • Yes. How do I close the question? – Arman Mojaver Apr 04 '20 at 10:48

0 Answers0