What is the difference between range and xrange functions in Python 2.X?

后端 未结 28 2631
深忆病人
深忆病人 2020-11-22 03:14

Apparently xrange is faster but I have no idea why it\'s faster (and no proof besides the anecdotal so far that it is faster) or what besides that is different about

28条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 04:16

    You will find the advantage of xrange over range in this simple example:

    import timeit
    
    t1 = timeit.default_timer()
    a = 0
    for i in xrange(1, 100000000):
        pass
    t2 = timeit.default_timer()
    
    print "time taken: ", (t2-t1)  # 4.49153590202 seconds
    
    t1 = timeit.default_timer()
    a = 0
    for i in range(1, 100000000):
        pass
    t2 = timeit.default_timer()
    
    print "time taken: ", (t2-t1)  # 7.04547905922 seconds
    

    The above example doesn't reflect anything substantially better in case of xrange.

    Now look at the following case where range is really really slow, compared to xrange.

    import timeit
    
    t1 = timeit.default_timer()
    a = 0
    for i in xrange(1, 100000000):
        if i == 10000:
            break
    t2 = timeit.default_timer()
    
    print "time taken: ", (t2-t1)  # 0.000764846801758 seconds
    
    t1 = timeit.default_timer()
    a = 0
    for i in range(1, 100000000):
        if i == 10000:
            break
    t2 = timeit.default_timer() 
    
    print "time taken: ", (t2-t1)  # 2.78506207466 seconds
    

    With range, it already creates a list from 0 to 100000000(time consuming), but xrange is a generator and it only generates numbers based on the need, that is, if the iteration continues.

    In Python-3, the implementation of the range functionality is same as that of xrange in Python-2, while they have done away with xrange in Python-3

    Happy Coding!!

提交回复
热议问题