How to use timer Timeit in Python

Source: Internet
Author: User
This article mainly introduces the use of the timer Timeit in Python, has a certain reference value, now share to everyone, the need for friends can refer to

This article describes how to use the timer Timeit in Python, and share it with you, as follows:

Timeit

Time.time () is usually used before and after a program, and then subtracted to get the run time of a program, but Python provides a more powerful timing library: Timeit

#导入timeit. Timeitfrom Timeit Import Timeit #看执行1000000次x =1 time: Timeit (' x=1 ') #看x =1 execution time, executed 1 times (number can be omitted, default value is 1000000) : Timeit (' x=1 ', number=1) #看一个列表生成器的执行时间, executed 1 times: Timeit (' [I-I in range (10000)] ', number=1) #看一个列表生成器的执行时间, Performed 10,000 times: Timeit (' [I-I in range] if i%2==0] ', number=10000)

To test the execution time of a function:

From Timeit import timeitdef func ():  s = 0 for  i in range:    s + = i  print (s) # Timeit (function name _ string, run Environment _ string, Number= run times) t = Timeit (' func () ', ' from __main__ import func ', number=1000) print (t)

This program tests the execution time of the function 1000 times

Repeat

Because the computer always has other programs are also occupying resources, your program is not the most efficient execution. As a result, many tests are performed, with the minimum execution time being the actual execution time.

From Timeit import repeatdef func ():  s = 0 for  i in range:    s + = I#repeat and Timeit usage are similar, with one repeat parameter, which means repeat test The number of times (can not be written, the default value is 3.), and the return value is a list of times. t = Repeat (' func () ', ' from __main__ import func ', number=100, repeat=5) print (t) print (min (t))

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.