Home > Article > Backend Development > 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:
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
>>> 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!