【发布时间】:2010-12-11 16:52:49
【问题描述】:
这是我编写的一个小程序,用于测量由于各种原因对我很重要的函数的速度:
import time,sys
count = 10 * 1000 * 1000
t1 = time.time()
d = dict()
for i in xrange(0,count):
d[i] = i
for i in xrange(0,count):
d[i] = d[i]*i
for i in xrange(0,count):
d[i] = d[i]-i
t2 = time.time()
print("time=%f" % (t2-t1))
print("size of dictionary: %d" % sys.getsizeof(d))
所以我在我的 mac 上用 Python2.7 运行它并得到:
$ python2.7 pyspeed.py
time= 7.24679493904
size of dictionary: 402653464
$ python2.7 pyspeed.py
time= 7.23868012428
size of dictionary: 402653464
$ python2.7 pyspeed.py
time= 7.26046490669
size of dictionary: 402653464
现在,当我尝试在 Python3.1 中运行它时,它当然不起作用,因为 xrange 已被贬值。我读过的所有文档都说 range 现在可以像 xrange 一样工作。所以这是重写的程序:
import time,sys
count = 10 * 1000 * 1000
t1 = time.time()
d = dict()
for i in range(0,count):
d[i] = i
for i in range(0,count):
d[i] = d[i]*i
for i in range(0,count):
d[i] = d[i]-i
t2 = time.time()
print("time=%f" % (t2-t1))
print("size of dictionary: %d" % sys.getsizeof(d))
以及Python3.1的表现:
$ python3.1 pyspeed.py
time=7.869891
size of dictionary: 402653464
$ python3.1 pyspeed.py
time=7.849537
size of dictionary: 402653464
$ python3.1 pyspeed.py
time=7.879416
size of dictionary: 402653464
慢了 7%。
出于预感,我尝试在 Python2.7 下使用range 而不是xrange 运行程序,得到了几乎相同的结果:
$ python2.7 pyspeed.py
time=7.735200
size of dictionary: 402653464
$ python2.7 pyspeed.py
time=7.743711
size of dictionary: 402653464
$ python2.7 pyspeed.py
time=7.762192
size of dictionary: 402653464
这仍然优于 Python3.1,但不如使用 xrange 的 2.7。
在我看来是这样的:
- Python3.1 依然显着 比 Python2 慢。为什么不是 快点?
- 尽管文档声称,
range()在 Python3 不能正常工作xrange()在 Python2 中做过(至少 性能方面),它的工作方式range()做到了。
我在这里遗漏了什么吗?或者是时候开始放弃 Python 了吗?
【问题讨论】:
-
是的,是时候放弃 Python 了。是否有特定的承诺来提高使用已被破坏的范围进行循环的性能?这似乎是放弃语言的一个小理由,就像丢掉一个鞋子不喜欢你的女人一样。
-
您应该使用 timeit 模块来对 Python 中的代码进行计时。
-
微基准测试慢了 7%?为我哭泣一条河!
-
dis.dis()输出的比较可能很有启发性(并且可能会导致您可以提交错误报告)。 -
另外,这个基准是 1. 非常做作(甚至超过平均基准)和 2. 无论如何都是糟糕的代码(尝试
{i: (i * i - i) for i in range(count)})。
标签: python performance python-3.x