为什么Python的for循环对于大输入非线性? [英] Why are python's for loops so non-linear for large inputs?

查看:184
本文介绍了为什么Python的for循环对于大输入非线性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是基准的一些Python代码,我注意到一些奇怪的东西。我使用了下面的函数来测量循环遍历一个空的for循环的速度:

$ $ $ $ $ $ c $ def f(n):
t1 = time.time()
在范围内(n):
通过
print(time.time() - t1)
0.035 $ b , f(10 ** 7)大约 0.35 , f (10 ** 8)大约 3.5 f(10 ** 9) 35 。但是 f(10 ** 10)?好于 2000 。这当然是出乎意料的。为什么要花费60倍的时间来迭代10倍的元素呢?什么是python的for循环导致这个?这是python特定的,或者这是否发生在很多语言?

解决方案

当你得到 10 ^ 9 你得到32位整数范围。然后,Python3将您透明地移动到任意精度整数,这对于分配和使用来说要慢得多。

一般来说,处理这么大的数字是Python3比Python2(在许多系统上至少有64bit快速整数)慢很多的领域之一。从好的一面来看,python更容易使用,而溢出类型错误。


I was benchmarking some python code I noticed something strange. I used the following function to measure how fast it took to iterate through an empty for loop:

def f(n):
    t1 = time.time()
    for i in range(n):
        pass
    print(time.time() - t1)

f(10**6) prints about 0.035, f(10**7) about 0.35, f(10**8) about 3.5, and f(10**9) about 35. But f(10**10)? Well over 2000. That's certainly unexpected. Why would it take over 60 times as long to iterate through 10 times as many elements? What's with python's for loops that causes this? Is this python-specific, or does this occur in a lot of languages?

解决方案

When you get above 10^9 you get out of 32bit integer range. Python3 then transparently moves you onto arbitrary precision integers, which are much slower to allocate and use.

In general working with such big numbers is one of the areas where Python3 is a lot slower that Python2 (which at least had fast 64bit integers on many systems). On the good side it makes python easier to use, with fewer overflow type errors.

这篇关于为什么Python的for循环对于大输入非线性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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