(1)程序解读--向量化计算


```python
import numpy as np #导入 numpy 库
a = np.array([1,2,3,4]) #创建一个数据 a
print(a)
```

    [1 2 3 4]
    


```python
import time #导入时间库
a = np.random.rand(1000000)
b = np.random.rand(1000000) #通过 round 随机得到两个一百万维度的数组
#round(random.uniform(0.98,1.02), 6)
a1 = round(np.random.uniform(0.98,1.02), 6)
print (a1)
tic = time.time() #现在测量一下当前时间
print(tic)
```

    0.999623
    1531463081.1142578
    


```python
#向量化的版本
c = np.dot(a,b)   #c have function?
print(c)
toc = time.time()
print (toc-tic)
print('Vectorized version:' + str(1000*(toc-tic)) +'ms') 
#打印一下向量化的版本的时间
```

    249713.3867711901
    256.70468258857727
    Vectorized version:256704.68258857727ms
    


```python
#继续增加非向量化的版本
c = 0
tic = time.time()
print (a)
print (b)
for i in range(1000000):
    c += a[i]*b[i]
toc = time.time()
print(c)
print (toc-tic)
print('For loop:' + str(1000*(toc-tic)) + 'ms')
#打印 for 循环的版本的时间
```

    [0.71883677 0.72077145 0.80352039 ... 0.45707131 0.49601016 0.46281836]
    [0.57333717 0.34841184 0.16528058 ... 0.9825072  0.47965587 0.9696575 ]
    249713.3867711889
    0.957054615020752
    For loop:957.054615020752ms
    

猜你喜欢

转载自blog.csdn.net/as472780551/article/details/81031042