Speed comparison between incrementing count variable and enumerate

In Python, you may need a counter when turning a for statement in a sequence. : smiley: At that time, it seems that the easy way is to define a counter outside the for statement and increment it inside the for statement, or to get the counter using enumerate: relaxed: When I heard that story, I wondered which one could process faster: confused: So I decided to measure the speed: grin: Click here for the measurement code.

sptst.py


import time

def count(test):
    count=0
    start=time.time()
    for item in test:
        a=count
        b=item
        c=test[count]
        count+=1
    diff=time.time()-start
    return diff

def enumer(test):
    start=time.time()
    for count,item in enumerate(test):
        a=count
        b=item
        c=test[count]
    diff=time.time()-start
    return diff

test=[]
for i in range(100000):
    test.append("test")

loopNum=1000
summation=0
for i in range(loopNum):
    summation+=(count(test))/(enumer(test))

print(summation/loopNum)

In the for statement using count and the for statement using enumerate, I turned the list consisting of 100000 elements and tried to perform appropriate processing. : neckbeard: Each for statement is turned 1000 times, and the count shows how many times the time has reached on average. : neckbeard: As a result, it settled down to about 1.2. : anguished: In this case, the processing was light, so there seems to be a 1.2 times difference: no_mouth: When you need a counter in a for statement, it seems better to use enumerate than to define a variable outside and increment it: wink:

Recommended Posts

Speed comparison between incrementing count variable and enumerate
Speed comparison between CPython and PyPy
File write speed comparison experiment between python 2.7.9 and pypy 2.5.0
File open function in Python3 (difference between open and codecs.open and speed comparison)
speed difference between wsgi, Bottle and Flask
Speed comparison of murmurhash3, md5 and sha1
Create new file [Comparison between Bash and PowerShell]
[Ruby vs Python] Benchmark comparison between Rails and Flask
Image capture / OpenCV speed comparison with and without GPU