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

查看:89
本文介绍了为什么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天全站免登陆