什么是向量化? [英] What is vectorization?

查看:434
本文介绍了什么是向量化?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Python中向量化for循环是什么意思?还有另一种写嵌套的for循环的方法吗?

What does it mean to vectorize for-loops in Python? Is there another way to write nested for-loops?

我是Python的新手,在我的研究中,我总是遇到NumPy库.

I am new to Python and on my research, I always come across the NumPy library.

推荐答案

Python for循环本质上比C循环慢.

Python for loops are inherently slower than their C counterpart.

这就是为什么numpynumpy数组上提供矢量化操作的原因.它将通常在Python中执行的for循环推到C级别,这要快得多. numpy提供矢量化("C级for循环")替代方案,否则将需要以元素方式进行操作("Python级for循环").

This is why numpy offers vectorized actions on numpy arrays. It pushes the for loop you would usually do in Python down to the C level, which is much faster. numpy offers vectorized ("C level for loop") alternatives to things that otherwise would need to be done in an element-wise manner ("Python level for loop).

import numpy as np
from timeit import Timer

li = list(range(500000))
nump_arr = np.array(li)

def python_for():
    return [num + 1 for num in li]

def numpy_add():
    return nump_arr + 1

print(min(Timer(python_for).repeat(10, 10)))
print(min(Timer(numpy_add).repeat(10, 10)))

#  0.725692612368003
#  0.010465986942008954

numpy矢量化加法速度提高了70倍.

The numpy vectorized addition was x70 times faster.

这篇关于什么是向量化?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆