简体   繁体   English

是否有必要用numpy编写所有变量和循环?

[英]Is it necessary to write all the variables and the loop with numpy?

I saw someone trying to use python and numpy to do simulations.我看到有人试图使用 python 和 numpy 进行模拟。 However, it was quiet slow.然而,它安静缓慢。 I read his code and it turnes out to me that he only used numpy packages when dealing with the array/matrix calculation, and all the other variables and codes was defined in the python main console(ie for loops).我读了他的代码,结果我发现他在处理数组/矩阵计算时只使用了 numpy 包,所有其他变量和代码都在 python 主控制台(即 for 循环)中定义。

My questions are:我的问题是:

  1. Is it necessary to write all the variable as numpy variable, for example np.float in order to get the full capability of numpy package?是否有必要将所有变量都写为 numpy 变量,例如 np.float 以获得 numpy 包的全部功能?

  2. Also, as from what I'm understanding, python's for loop is quiet slow.另外,据我所知,python 的 for 循环很慢。 But I don't want to use cython for the sake of simplicity and readibility.但为了简单和可读性,我不想使用 cython。 It there a way for the numpy to use some special iteration process to accelerate the calculation? numpy 有没有办法使用一些特殊的迭代过程来加速计算? I saw a page that looks like it but did not quite understand( https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html ).我看到一个看起来像但不太明白的页面( https://docs.scipy.org/doc/numpy/reference/arrays.nditer.html )。 Bascially, how to utilize the full capability ofnumpy package?基本上,如何利用 numpy 包的全部功能?

Since you didn't provide details of your program, I'll assume you are wondering if numpy.ndarray is faster than using normal python loop.由于您没有提供程序的详细信息,我假设您想知道 numpy.ndarray 是否比使用普通 python 循环更快。

Yes, it IS much faster.是的,它要快得多。

It's called vectorization.这称为矢量化。 It's faster because:它更快,因为:

  1. It'll be executed by the precompiled C/C++ library and thus faster than executing python script它将由预编译的 C/C++ 库执行,因此比执行 python 脚本更快
  2. It takes advantage of the architecture of modern CPU.它利用了现代 CPU 的架构。 See: link见: 链接

That said, it also depends on what you want to do with it.也就是说,这也取决于你想用它做什么。 If you are performing math/matrix operations, than vectorization also provides better readability (since it just looks similar to the equation) and more boost since the operations are mostly numerical.如果您正在执行数学/矩阵运算,那么矢量化还提供更好的可读性(因为它看起来与等式相似)和更多的提升,因为运算主要是数值。 If the operations are not numerical, than you'll get less boost and thus can do it the python way.如果操作不是数字,那么你得到的提升会更少,因此可以用 python 的方式来做。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM