LoginSignup
1

More than 5 years have passed since last update.

The performance comparison between numpy and scipy

Last updated at Posted at 2017-12-28
import numpy as np
import time
import scipy
import scipy.spatial

def numpy_and_scipy(R,C,sm=0):
 print("====R:"+str(R)+",C:"+str(C)+"====")
 s = time.time()
 Z = np.random.random((R,C))
 X,Y = np.atleast_2d(Z[:,0], Z[:,1])
 D = np.sqrt( (X-X.T)**2 + (Y-Y.T)**2)
 if (sm): print(D)
 print("numpy_time:"+str(time.time() - s))
 s = time.time()
 Z = np.random.random((R,C))
 D = scipy.spatial.distance.cdist(Z,Z)
 if (sm): print(D)
 print("scipy_time:"+str(time.time() - s))

numpy_and_scipy(4,4,1)
numpy_and_scipy(10,5)
numpy_and_scipy(5,10)
numpy_and_scipy(400,400)
numpy_and_scipy(10,1000)
numpy_and_scipy(1000,10)
====R:4,C:4====
[[ 0.          0.24744957  0.39208288  0.37222202]
 [ 0.24744957  0.          0.1923926   0.33487354]
 [ 0.39208288  0.1923926   0.          0.25010424]
 [ 0.37222202  0.33487354  0.25010424  0.        ]]
numpy_time:0.0005698204040527344
[[ 0.          0.66546531  0.72838154  0.95408877]
 [ 0.66546531  0.          0.8761849   1.08838767]
 [ 0.72838154  0.8761849   0.          0.78060971]
 [ 0.95408877  1.08838767  0.78060971  0.        ]]
scipy_time:0.0003790855407714844
====R:10,C:5====
numpy_time:3.981590270996094e-05
scipy_time:2.574920654296875e-05
====R:5,C:10====
numpy_time:2.6226043701171875e-05
scipy_time:2.002716064453125e-05
====R:400,C:400====
numpy_time:0.004547834396362305
scipy_time:0.05216693878173828
====R:10,C:1000====
numpy_time:0.00023102760314941406
scipy_time:0.00028324127197265625
====R:1000,C:10====
numpy_time:0.016072988510131836
scipy_time:0.00795292854309082
  • scipy is not always faster than numpy, but scipy might be more efficient in the matrix of more rows.

Refs.

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1