简体   繁体   中英

How is reversed function in python implemented?

I have been trying to reverse a list in python using in place reordering of elements
using

def reverseArray(a):

    for i in range(int(len(a) / 2)):
        temp = a[i]
        a[i] = a[len(a) - i - 1]
        a[len(a) - i - 1] = temp

    return a

and I used the following script for running the benchmark

for s in range(20):
    a = [i for i in range(30002023)]
    tick = time.time()
    reverseArray(a)
    tok = time.time()
    print(f"tok-tick:{tok-tick}")

which gave me the following output

tok-tick:5.572033643722534
tok-tick:5.721977472305298
tok-tick:6.386164665222168
tok-tick:7.384392738342285
tok-tick:10.91420841217041
tok-tick:7.937604904174805
tok-tick:6.611226320266724
tok-tick:5.531114339828491
tok-tick:6.300005674362183
tok-tick:5.5767083168029785
tok-tick:5.933243274688721
tok-tick:5.885504961013794
tok-tick:5.496972560882568
tok-tick:5.854052543640137
tok-tick:5.983134984970093
tok-tick:5.644777059555054
tok-tick:6.585403680801392
tok-tick:6.760901927947998
tok-tick:5.675948619842529
tok-tick:6.09527063369751

BUT when I ran the predefined function on the same benchmark using the reverse array function using

def reverseArray(a):
    return [ e for e in reversed(a)]

I got the following output

tok-tick:0.9134881496429443
tok-tick:0.922814130783081
tok-tick:0.9020524024963379
tok-tick:0.9431264400482178
tok-tick:0.8796248435974121
tok-tick:0.9475719928741455
tok-tick:0.9039063453674316
tok-tick:0.9342403411865234
tok-tick:0.8823723793029785
tok-tick:0.9073545932769775
tok-tick:0.869114875793457
tok-tick:0.899376630783081
tok-tick:0.8696825504302979
tok-tick:0.9529657363891602
tok-tick:0.8960628509521484
tok-tick:0.9192886352539062
tok-tick:0.9400691986083984
tok-tick:0.9219272136688232
tok-tick:0.8531026840209961
tok-tick:0.9414753913879395

I really want to know why there is this huge difference in performance?

It's faster for lists because list is a builtin type and its __reversed__ method is implemented in C , which is of course faster than plain Python.

Python itself is written in C and the interpreter executes byte code that is generated from your Python code. In a sense, each instruction of this bytecode is a C function. As you can check using the dis module , your code actually compiles to a lot of instructions - many calls to C. But list.__reversed__ is in a way one single C function. Calling one function is of course faster than calling many.

I'm saying "in a sense" and "in a way" because it's not actually implemented a little bit differently: bytecode instructions are a part of one huge function, but it doesn't really make any difference.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM