Python timing function-timeit Module

Source: Internet
Author: User

The most important thing you need to know about Python code optimization is that you never have to write timing functions yourself.

Timing for a very short code is complicated. How long does the processor have to run this code? Is there anything running in the background? Every modern computer runs continuous or intermittent programs in the background. A small negligence may damage your plan for a hundred years. The background service is occasionally "awakened" to make some emails in the last 1‰ seconds, connect to the timer Communication Server, Check application updates, and scan viruses, check whether a disk is inserted into the optical drive. Shut down and disconnect the network before starting the timing test. Once again confirm that everything is closed, turn off the services that constantly check whether the network is restored, and so on.

The next step is the changing factors introduced by the timing framework itself. Does the python interpreter cache method name searches? Is the compilation result of the code block cached? What about regular expressions? Is there any side effect when your code is repeated? Don't forget that your work results will be presented in units smaller than the second, and small errors in your timing framework will cause irreparable results distortion.

The Python community has a saying: "Python has its own battery ." Do not write the timing framework by yourself. Python 2.3 hasTimeitThe perfect timing tool.

Example 18.2. TimeitIntroduction

If you have not downloaded the sample program included in this book, you can download this program and other sample programs.

>>> import timeit
>>> t = timeit.Timer("soundex.soundex('Pilgrim')",
... "import soundex")
>>> t.timeit()
8.21683733547
>>> t.repeat(3, 2000000)
[16.48319309109, 16.46128984923, 16.44203948912]
TimeitThe module definesTimerClass. Both parameters are strings. The first parameter is the statement you want to time. Here, what you want to time is'Pilgrim'The parameter calls the soundex function. PassTimerThe second parameter is the import statement used to build the environment for the first parameter statement. Internally,TimeitBuild an independent virtual environment and manually execute the creation Statement (ImportSoundexModule), and then manually compile and execute the timing Statement (call the soundex function ).
If you haveTimerObject, the simplest thing is to callTimeit ()It calls your function 1 million times and returns the number of seconds it takes.
TimerAnother main method of the object isRepeat ()It accepts two optional parameters. The first parameter is the number of times the entire test is repeated, and the second parameter is the number of times the timing statement is called in each test. Both parameters are optional and Their default values are3And1000000.Repeat ()Method returns the list of time consumed by each test cycle recorded in seconds.

You can useTimeitModule to test an existing Python program without modifying the code. View the contents of command line options in the http://docs.python.org/lib/node396.html document.

Note:Repeat ()Returns a time list. Because of the tiny changes in the processing time used by the python timer (or the nasty background processes that you cannot eradicate), it is almost impossible to repeat these times. Your first thought may be: "Let's calculate the average value to obtain real data ."

In fact, it is almost a definite mistake. Changes to your code or Python interpreter may reduce time consumption, and those factors other than the hateful background process or other Python interpreter that cannot be removed may prolong the time consumption. If the difference between timing results exceeds a few percent, too many variable factors make you unable to trust the results. If not, you can take the minimum value and discard other results.

Python has a convenientMinThe function returns the minimum value in the input list:

>>> min(t.repeat(3, 1000000))
8.22203948912

TimeitThe module is used only when you know which code segment needs optimization. If you have a large python program that does not know your performance problems, ViewHotshotModule.

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.