Home  >  Article  >  Backend Development  >  How Can Python\'s `timeit` Module Be Used to Compare Code Execution Times?

How Can Python\'s `timeit` Module Be Used to Compare Code Execution Times?

Susan Sarandon
Susan SarandonOriginal
2024-11-25 02:51:18990browse

How Can Python's `timeit` Module Be Used to Compare Code Execution Times?

Time Performance Comparison with the timeit Module

The timeit module is a powerful tool for measuring the performance of code snippets. It can be used to compare the execution times of different algorithms or implementations.

Interactive Usage

In an interactive Python session, there are two ways to use timeit:

  1. IPython Shell: The IPython shell provides a special %timeit function:
In [1]: def f(x):
   ...:     return x*x
   ...: 

In [2]: %timeit for x in range(100): f(x)
100000 loops, best of 3: 20.3 us per loop
  1. Standard Python Interpreter: In a standard Python interpreter, you can import functions defined earlier in the session from the main module:
>>> def f(x):
...     return x * x 
... 

>>> import timeit
>>> timeit.repeat("for x in range(100): f(x)", "from __main__ import f", number=100000)
[2.0640320777893066, 2.0876040458679199, 2.0520210266113281]

The above is the detailed content of How Can Python\'s `timeit` Module Be Used to Compare Code Execution Times?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn