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

后端 未结 28 2072
深忆病人
深忆病人 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:08

    When testing range against xrange in a loop (I know I should use timeit, but this was swiftly hacked up from memory using a simple list comprehension example) I found the following:

    import time
    
    for x in range(1, 10):
    
        t = time.time()
        [v*10 for v in range(1, 10000)]
        print "range:  %.4f" % ((time.time()-t)*100)
    
        t = time.time()
        [v*10 for v in xrange(1, 10000)]
        print "xrange: %.4f" % ((time.time()-t)*100)
    

    which gives:

    $python range_tests.py
    range:  0.4273
    xrange: 0.3733
    range:  0.3881
    xrange: 0.3507
    range:  0.3712
    xrange: 0.3565
    range:  0.4031
    xrange: 0.3558
    range:  0.3714
    xrange: 0.3520
    range:  0.3834
    xrange: 0.3546
    range:  0.3717
    xrange: 0.3511
    range:  0.3745
    xrange: 0.3523
    range:  0.3858
    xrange: 0.3997 <- garbage collection?
    

    Or, using xrange in the for loop:

    range:  0.4172
    xrange: 0.3701
    range:  0.3840
    xrange: 0.3547
    range:  0.3830
    xrange: 0.3862 <- garbage collection?
    range:  0.4019
    xrange: 0.3532
    range:  0.3738
    xrange: 0.3726
    range:  0.3762
    xrange: 0.3533
    range:  0.3710
    xrange: 0.3509
    range:  0.3738
    xrange: 0.3512
    range:  0.3703
    xrange: 0.3509
    

    Is my snippet testing properly? Any comments on the slower instance of xrange? Or a better example :-)

提交回复
热议问题