【问题标题】:What is faster: Python3's 'len' or numpys shape?什么更快:numpy 形状的 Python 'len'?
【发布时间】:2016-02-22 07:19:28
【问题描述】:

我有一个坐标数组:

points = [x,y]

具有 (numpy) 尺寸/形状:(18, 1, 2)

在 matlab 中,要初始化一个数组以用 '3' 索引这些点,我可以这样做:

A = ones(size(points,1),1)*3'

我怎样才能以最快的方式使用 python3 和 numpy 做到这一点?

【问题讨论】:

    标签: python python-3.x opencv numpy


    【解决方案1】:

    正常的numpy 等效项是

    np.ones((points.shape[0],1))*3
    

    shape 是数组的一个属性,因此访问它本质上是瞬时的。它不需要做任何计算。

    In [277]: points.shape
    Out[277]: (18, 1, 2)
    In [278]: points.size   # number of elements
    Out[278]: 36
    In [279]: len(points)  # size of the 1st dimension
    Out[279]: 18
    

    在上面的np.ones... 表达式中,shapelen() 只占计算时间的很小一部分。使用哪个并不重要。但是shape 更通用,例如。 np.ones(points.shape[:2]) 将给出相同的 (18,1) 数组。

    【讨论】:

      【解决方案2】:
          def time_compare(self):
              loops = 100000000
              start = time.time()
              for i in range(loops):
                  self.value_map.shape[0]
                  self.value_map[0].shape[0]
                  self.value_map[0][0].shape[0]
                  self.value_map[0][0][0].shape[0]
              end = time.time()
              timed = (end - start)
              print("shape={}".format(timed))
      
              start = time.time()
              for i in range(loops):
                  len(self.value_map)
                  len(self.value_map[0])
                  len(self.value_map[0][0])
                  len(self.value_map[0][0][0])
              end = time.time()
              timed = (end - start)
              print("len={}".format(timed))
      

      形状=102.26551818847656
      len=87.99720764160156

      len 比 shape 快

      【讨论】:

        猜你喜欢
        • 2014-08-25
        • 2013-12-16
        • 2018-05-13
        • 1970-01-01
        • 1970-01-01
        • 2017-08-22
        • 1970-01-01
        • 1970-01-01
        • 2016-05-15
        相关资源
        最近更新 更多