为什么CPython和pypy中的流语句在性能上存在相对和绝对的差异?

2024-05-13 17:49:36 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在读《学习python》(由Mark Lutz编写)一书,我使用书中的一个程序来测量流语句之间的差异。由于我目前在一个项目中工作,我想知道pypypy比我的标准python3.7快多少,我猜它是在C虚拟机中运行的。然而,当我运行该程序时,我惊讶地发现,根据我选择运行的实现,flow语句之间的相对和绝对性能存在层次差异。有人知道为什么会这样吗

以下是我使用的代码和以下两个输出:

# File timeseqs.py
"Test the relative speed of iteration tool alternatives."
import sys, timer # Import timer functions
reps = 10000
repslist = list(range(reps)) # Hoist out, list in both 2.X/3.X
def forLoop():
    res = []
    for x in repslist:
        res.append(abs(x))
    return res
def listComp():
    return [abs(x) for x in repslist]
def mapCall():
    return list(map(abs, repslist)) # Use list() here in 3.X only!
# return map(abs, repslist)
def genExpr():
    return list(abs(x) for x in repslist) # list() required to force results
def genFunc():
    def gen():
        for x in repslist:
            yield abs(x)
            return list(gen()) # list() required to force results
print(sys.version)
for test in (forLoop, listComp, mapCall, genExpr, genFunc):
    #(bestof, (total, result)) = timer.bestoftotal(5, 1000, test)
    print ('%-9s: %.5f => [%s...%s]' %(test.__name__, bestof, result[0], result[-1]))

Python 3.7中的输出:

3.7.5 (default, Oct 25 2019, 15:51:11) 
[GCC 7.3.0]
forLoop  : 3.08886 => [0...9999]
listComp : 1.77405 => [0...9999]
mapCall  : 0.68121 => [0...9999]
genExpr  : 2.43599 => [0...9999]

Py3中的输出:

3.6.9 (5da45ced70e515f94686be0df47c59abd1348ebc, Oct 18 2019, 07:48:38)
[PyPy 7.2.0 with GCC 7.3.0]
forLoop  : 0.40884 => [0...9999]
listComp : 0.47015 => [0...9999]
mapCall  : 0.39428 => [0...9999]
genExpr  : 0.54222 => [0...9999]

Tags: intestforreturndefresabsresult