Julia 和 Python,哪一个更快?( 二 )


end
 

  •  
    end
     
  •  
    @time MM
     
  •  
     
  •  
    0.000001 seconds
     
  •  
    MM (generic function with 1 method)
     
  •  
    Julia 使用库耗时 0.000017 秒,使用循环耗时 0.000001 秒 。
    使用 Python 编写相同的矩阵乘法程序如下 。从结果可以发现,与不使用库相比,使用库的程序花费的时间更少:
     
    1.  
      import numpy as np
       
    2.  
      import time as t
       
    3.  
      x = np.random.rand(10,10)
       
    4.  
      y = np.random.rand(10,10)
       
    5.  
      start = t.time()
       
    6.  
      z = np.dot(x, y)
       
    7.  
      print(“Time = “,t.time()-start)
       
    8.  
      Time = 0.001316070556640625
       
    9.  
       
    10.  
      import random
       
    11.  
      import time as t
       
    12.  
      l = 0
       
    13.  
      h= 10
       
    14.  
      cols = 10
       
    15.  
      rows= 10
       
    16.  
       
    17.  
      choices = list (map(float, range(l,h)))
       
    18.  
      x = [random.choices (choices , k=cols) for _ in range(rows)]
       
    19.  
      y = [random.choices (choices , k=cols) for _ in range(rows)]
       
    20.  
       
    21.  
      result = [([0]*cols) for i in range (rows)]
       
    22.  
       
    23.  
      start = t.time()
       
    24.  
       
    25.  
      for i in range(len(x)):
       
    26.  
      for j in range(len(y[0])):
       
    27.  
      for k in range(len(result)):
       
    28.  
      result[i][j] += x[i][k] * y[k][j]
       
    29.  
       
    30.  
      print(result)
       
    31.  
      print(“Time = “, t.time()-start)
       
    32.  
       
    33.  
      Time = 0.0015912055969238281
       
     
    Python 使用库耗时 0.0013 秒,使用循环耗时 0.0015 秒 。
    线性搜索
    我们进行的下一个实验是对十万个随机生成的数字进行线性搜索 。这里使用了两种方法,一种是使用for循环,另一种是使用运算符 。我们使用 1 到 1000 的整数执行了 1000 次搜索,正如你在下面的输出中看到的那样,我们还打印了我们在数据集中找到了多少个整数 。下面给出了使用循环和使用IN运算符的时间 。这里我们使用了 CPU 3 次运行时间的中位数 。
    使用 Julia 编写的程序和运行结果如下:
    (LCTT 译注:此处原文缺失 Julia 代码)
    使用 Python 编写的程序和运行结果如下:
     
    1.  
      import numpy as np
       
    2.  
      import time as t
       
    3.  
      x = np.random.rand(10,10)
       
    4.  
      y = np.random.rand(10,10)
       
    5.  
      start = t.time()
       
    6.  
      z = np.dot(x, y)
       


      推荐阅读