TIME advantage by using Vectorization

Time advantage by using Vectorization

Vectorization reduce the calculation time comparing to for loop, especially when dealing with the large data set. Here gives an example.

Example in Python


    import numpy as np
    import time
    #产生随机数,a与b都是一个一维向量
    a = np.random.rand(4000000)
    b = np.random.rand(4000000)
    #利用np.dot(a,b)计算两向量数乘
    tic = time.time()#计算程序运行到这里的时间
    c = np.dot(a,b)
    toc = time.time()
    
    print(c)
    print("vectorization:"+str(1000*(toc-tic))+"ms")
    #利用循环计算两向量数乘
    c = 0
    tic = time.time()
    for i in range(4000000):
        c += a[i]*b[i]
    toc = time.time()
    
    print(c)
    print("non-vectorization:"+str(1000*(toc-tic))+"ms")

Result is as follows:

1000250.5707573969
vectorization:4.027366638183594ms
1000250.5707574325
non-vectorization:1999.9730587005615ms

Conclusion

Using vectorization can largely reduce the calculation time.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值