为什么 NumPy 数组这么快? [英] Why are NumPy arrays so fast?

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

问题描述

我刚刚更改了我正在编写的程序,以将我的数据保存为 numpy 数组,因为我遇到了性能问题,这种差异令人难以置信.原先运行需要 30 分钟,现在只需 2.5 秒!

I just changed a program I am writing to hold my data as numpy arrays as I was having performance issues, and the difference was incredible. It originally took 30 minutes to run and now takes 2.5 seconds!

我想知道它是怎么做到的.我认为是因为它消除了对 for 循环的需要,但除此之外我很难过.

I was wondering how it does it. I assume it is that the because it removes the need for for loops but beyond that I am stumped.

推荐答案

Numpy 数组是密集排列的同构数组.相比之下,Python 列表是指向对象的指针数组,即使它们都是相同的类型.因此,您可以获得参考位置的好处.

Numpy arrays are densely packed arrays of homogeneous type. Python lists, by contrast, are arrays of pointers to objects, even when all of them are of the same type. So, you get the benefits of locality of reference.

此外,许多 Numpy 操作是用 C 实现的,避免了 Python 中循环、指针间接和每元素动态类型检查的一般成本.速度提升取决于您执行的操作,但几个数量级在数字运算程序中并不少见.

Also, many Numpy operations are implemented in C, avoiding the general cost of loops in Python, pointer indirection and per-element dynamic type checking. The speed boost depends on which operations you're performing, but a few orders of magnitude isn't uncommon in number crunching programs.

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

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