In python, range () and xrange () Usage Analysis, pythonxrange

Source: Internet
Author: User

In python, range () and xrange () Usage Analysis, pythonxrange

This article describes the usage of range () and xrange () in python. We will share this with you for your reference. The details are as follows:

It is said that range is more overhead than xrange because range directly generates a list object, and xrange returns a value in each call (refer to: http://www.bkjia.com/article/50072.htm ). So curious, I made a small test to compare the performance of the two functions.

(1) test code

#! /Usr/bin/env pythonfrom datetime import * def test_range (): c1 = 0 t1 = datetime. now () for I in range (0,100000): c1 + = 1 print datetime. now ()-t1def test_xrange (): c1 = 0 t1 = datetime. now () for I in xrange (0,100000): c1 + = 1 print datetime. now ()-t1if _ name _ = '_ main _': test_range () test_xrange ()

(2) running result

(3) Summary

From the three running results, we can see that range is about 70% more than xrange in the same amount of computing. In addition, the ratio is basically maintained in different computing scenarios. Therefore, xrange is a good choice if you do not need to return a list object.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.