【发布时间】:2015-08-11 18:31:27
【问题描述】:
我正在尝试在 Python 中计算逻辑方程的第 n 个值。使用循环很容易做到这一点:
import timeit
tic = timeit.default_timer()
x = 0.23
i = 0
n = 1000000000
while (i < n):
x = 4 * x * (1 - x)
i += 1
toc = timeit.default_timer()
toc - tic
但是,它通常也很耗时。正如 abarnert 在 Is MATLAB faster than Python (little simple experiment) 中所建议的那样,在 PyPy 中执行此操作可大大提高性能。
我还被建议避免使用 Python 循环并改用 NumPy 数组和向量操作 - 实际上我看不出这些有什么帮助(在我看来,NumPy 操作类似于 Matlab 的操作,我不知道有任何上面的代码也可以在 Matlab 中进行矢量化)。
有没有办法在没有循环的情况下优化代码?
【问题讨论】:
标签: performance python-3.x for-loop numpy vectorization