gnumpy numpy 性能对比

要开始做实验,写代码了,想自己写一下工具,偏机器学习的,要用到矩阵运算比较多,于是想对numpy 的效率进行一下探索。

版本一

首先简单看一下矩阵乘法的结果,只用numpy:

import numpy as np
n = 4000
for i in range(10):
    a = np.random.uniform(low=0., high=1., size=(n, n)).astype(np.float32)    b = np.random.uniform(low=0., high=1., size=(n, n)).astype(np.float32)
    a = a.dot(b)


版本二

用cython加速一下,看看效果,

首先,改一下后缀,用pyx

然后运行:

cython bench_numpy_c.pyx

写一个setup.py文件:

from distutils.core import setup
from Cython.Build import cythonize

setup(
  name = 'bench_numpy_c',
  ext_modules = cythonize("bench_numpy_c.pyx"),
)

然后编译:

 python setup.py build_ext --inplace



版本三

然后用GPU加速一下,先装cudamat,然后使用gnumpy:

import gnumpy as gpu 
import numpy as np
n = 4000
for i in range(10):
    a = np.random.uniform(low=0., high=1., size=(n, n)).astype(np.float32)    b = np.random.uniform(low=0., high=1., size=(n, n)).astype(np.float32)
    ga = gpu.garray(a)
    gb = gpu.garray(b)

    ga = ga.dot(gb)


最后,总体来测试一下效果,用timeit模块,代码如下:

from timeit import Timer

t1 =Timer('bench_numpy.test()','import bench_numpy')
t2 =Timer('bench_numpy_c.test()','import bench_numpy_c')
t3 =Timer('bench_gnumpy.test()','import bench_gnumpy')
print "pure   numpy cost: %f s"%t1.timeit(1)
print "cython numpy cost: %f s"%t2.timeit(1)
print "using gnumpy cost: %f s"%t3.timeit(1)
print "test 10 times"
print "pure   numpy cost: %f s"%t1.timeit(10)
print "cython numpy cost: %f s"%t2.timeit(10)
print "using gnumpy cost: %f s"%t3.timeit(10)

结果:cython加速了一点点而已,但是gnumpy加速了不少,2-3倍

[test@localhost benchmarkNumpy]$ python benchmark.py 
pure   numpy cost: 2.523334 s
cython numpy cost: 2.515121 s
gnumpy: failed to use gpu_lock. Using board #0 without knowing whether it is in use or not.
using gnumpy cost: 1.700691 s
test 10 times
pure   numpy cost: 25.952191 s
cython numpy cost: 25.452048 s
using gnumpy cost: 7.745144 s


试试 100次循环:

pure   numpy cost: 250.188029 s
cython numpy cost: 251.585954 s
gnumpy: failed to use gpu_lock. Using board #0 without knowing whether it is in use or not.
using gnumpy cost: 78.827483 s

还是gpu提升速度比较多,简单的提升了三倍左右的速度。

以后有时间再探索一下numpy的c api 接口什么的


评论发不了链接。。。

cudamat 安装文档:https://github.com/cudamat/cudamat/blob/master/INSTALL.md

gnumpy 网址: http://www.cs.toronto.edu/~tijmen/gnumpy.html




评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值