numpy庫和for迴圈效率比較

2021-10-03 12:18:44 字數 2410 閱讀 3474

numpy庫和for迴圈效率比較:(原因分析在最後的鏈結中)

對於numpy的矩陣v,還可以使用np.log(v),np.abs(v),np.maximum(), v**2, 1/v等操作

import numpy as np

defmf

(x,y)

:return x **3+

2* x -

1if x > y else x *3+

8f = np.vectorize(mf)

a = np.random.randint(-10

,10,size=(6

,6))

result_array = f(a,

2)

a
array([[ -7,  -6,  -5,  -2,   0,  -5],

[ 5, 5, 0, 7, -2, -9],

[ -6, 3, -5, -6, -2, -8],

[-10, -5, 3, -6, 7, 5],

[ -9, -7, 5, 3, -2, 2],

[ -2, -2, 6, -6, 2, 9]])

result_array
array([[-13, -10,  -7,   2,   8,  -7],

[134, 134, 8, 356, 2, -19],

[-10, 32, -7, -10, 2, -16],

[-22, -7, 32, -10, 356, 134],

[-19, -13, 134, 32, 2, 14],

[ 2, 2, 227, -10, 14, 746]])

原因: numpy是建立在對向量數**算進行了很多艱苦優化的低階庫之上的,它和for迴圈的內部細節不同,優化很複雜,參考乙個例子:fast inverse square root,更多原因參考:is using numpy faster than using for-loops to handle lists, and why?

原始碼分析foreach效率比for迴圈高

首先看看php原始碼變數值儲存 typedef union zvalue value str hashtable ht hash table value zend object value obj zvalue value php陣列的值儲存在zvalue value.ht裡面,它是乙個hashta...

mybatis exists 和in 的效率比較

這條語句適用於a錶比b表大的情況 select from ecs goods a where cat id in select cat id from ecs category 這條語句適用於b錶比a表大的情況 select from ecs goods a where exists select ...

is file和file exists效率比較

目前在弄檔案快取的時候用到了判定檔案存在與否,is file 還是file exists 呢?is file和file exists兩者效率比較起來,誰的執行速度更快呢?還是做個測試吧 12 3456 78910 1112 1314 1516 1718 1920 2122 23 start time...