做 OJ 时为什么 Python3 慢过 Python2?

2017-03-07 23:10:04 +08:00
 charadeyouare

PAT Basic 1028 https://www.patest.cn/contests/pat-b-practise/1028 思路很简单,但用 py3 老是在最后一个测试点超时,在网上找的 py2 答案却没这个问题。 PAT 提供 3.4.2 和 2.7.9 。抄来的代码如下。把 raw_input 和 print 改了也没用...

from sys import exit    

def isValid( birth ):
    if birth <= "2014/09/06" and birth >= "1814/09/06":
        return 0
    else:
         return 1    

str = raw_input()
num = int(str)
max = []
min = []
validNum = 0    

for i in range(num):
    tmp = raw_input().split()
    if isValid( tmp[1] ) == 0:
        validNum += 1                              
        if len(max) == 0 or max[1] > tmp[1]:
            max = tmp    

        if len(min) == 0 or min[1] < tmp[1]:
            min = tmp
if len(max) != 0:
    print validNum, max[0], min[0]
else:
    print '0'    

exit(0)
3298 次点击
所在节点    Python
10 条回复
wingyiu
2017-03-08 00:08:30 +08:00
py3 就是比 py2 慢,至少 3.6 之前是
NoAnyLove
2017-03-08 04:20:29 +08:00
我一直以为 Python 3 比 Python 2 快来着。。。。。。。 Orz

具体还是应该看代码吧,比如 Python 3 中大量使用了生成器,`xrange`取消了,`range`的效果等同于 Python 2 中的`xrange`,但是 Python 3 的`range`要比 Python 2 的`xrange`慢不少,看这里:

```
$ python3 -m timeit -s"r = range(33550336)" "for i in r: pass"
10 loops, best of 3: 835 msec per loop

$ python2 -m timeit -s"r = xrange(33550336)" "for i in r: pass"
10 loops, best of 3: 464 msec per loop
```

代码来自: https://mail.python.org/pipermail/python-list/2011-August/609571.html

还有很多 filter 、 map 之类的函数都变成了返回生成器一样的对象。
但是。。。。。为啥 Python 3 比 Python 2 慢啊?这不科学啊。。。。
NoAnyLove
2017-03-08 04:21:52 +08:00
@wingyiu 为啥? Python 3.6 有什么大的改进吗?
uxstone
2017-03-08 09:46:51 +08:00
都 python 了,没必要比这点快慢了吧......
开发快才是真的快
charadeyouare
2017-03-08 10:10:22 +08:00
@uxstone 刷题也快,能用 py 过就肯定用 py 。
XYxe
2017-03-08 16:28:24 +08:00
应该和 dict 的效率有很大的关系吧
charadeyouare
2017-03-08 18:20:47 +08:00
@XYxe 没用到 dict 啊。但 dict 基于 hashmap , get 的效率不低吧?
XYxe
2017-03-08 19:11:42 +08:00
@charadeyouare Python 内部用到 dict 的地方很多啊,比如说在交互模式下,`a=1`一共会创建并销毁 15 个字典对象。我这里测试 2.7 和 3.5 dict 的效率差很多啊。
charadeyouare
2017-03-08 19:38:07 +08:00
@XYxe 这就尴尬了, 3.6 会比 2.7 快吗?
NoAnyLove
2017-03-09 01:06:09 +08:00
@uxstone 刷题有影响。有些时候一个相同的算法,用 C/C++/Java 都能过, Python 却会 TLE , Orz

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/345727

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX