Why are there relative and absolut differences in performance among flow statements in CPython and pypy?

早过忘川 提交于 2020-01-16 12:00:09

问题


I'm reading the book Learning python (by Mark Lutz) and I use one of the programs shown in the book to measure the difference between flow statements. As I'm working in a project currently, I would like to know how faster pypy can be than my standard Python 3.7, which I guess is running in a C virtual machine. However, when I ran the program I was surprised to discover that there are hierarchical differences in relative and absolute performance among the flow statements depending on which implementation I chose to run. Does someone know why this happened?

Here is the code I used and the following two outputs:

# 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]))

Output in 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]

Output in pypy3:

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]

来源:https://stackoverflow.com/questions/59161250/why-are-there-relative-and-absolut-differences-in-performance-among-flow-stateme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!