向量相加其一(Python & Numpy速度对比)

向量相加其一


pytorch、tensorflow的底层框架很多地方都是用C语言和GPU加速的
其中向量加是最基础的

今天先给向量相加开个头,是向量相加的纯python和numpy实现
先给出测试机的的信息

硬件信息

CPU
厂家:Intel
型号:Intel®Pentium® CPU 5405U
核数:4
频率:2.3GHz 2.3GHz
指令集:不支持AVX2/AVX512
GPU1
厂家:Intel
型号:Intel®UHD Graphics 610
显存容量:120MB
显存频率:300MHz
显存带宽:17.1GB/s
GPU2
厂家:NVIDIA
型号:NVIDIA GeForce MX250
显存容量:2GB
显存频率:1519MHz
显存带宽:48.1GB/s

源代码

import time
import numpy as np

n = 1000000
repeat = 10 # CPU运算具有偶然性,计10次计算时间取平均

# 初始化
a = np.zeros((n,), dtype=int)
a[:] = 1

b = np.zeros((n,), dtype=int)
b[:] = 2

c1 = np.zeros((n,), dtype=int)
c2 = np.zeros((n,), dtype=int)

t0 = time.time()
for i in range(repeat):
    c1 = np.add(a, b)
t1 = time.time()
runtime = (t1 - t0) / repeat
print('numpy takes', runtime, 'sec')

t0 = time.time()
for i in range(repeat):
    for j in range(n):
        c2[j] = a[j] + b[j]
t1 = time.time()
runtime = (t1 - t0) / repeat
print('python loop takes', runtime, 'sec')

结果

可以看出numpy加速效果是很显著的,在10的6次方这个数量级下,2个一维向量相加numpy对python loop的加速比为172.68。
这也揭示了为什么numpy作为向量计算的首选第三方库
在这里插入图片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章