Home >Backend Development >Python Tutorial >How Can Python\'s `timeit` Module Help Compare the Performance of Different Sorting Algorithms?
Comparing Function Performance with the timeit Module
The timeit module provides a versatile tool for measuring the execution times of Python functions. To compare the performance of your own functions, such as "insertion_sort" and "tim_sort", follow these steps:
Interactive Python Session (IPython Shell):
In [1]: def insertion_sort(array): ...: # your code for insertion sort ...: In [2]: %timeit for _ in range(100): insertion_sort(array) 1000 loops, best of 3: 25.6 us per loop
>>> import timeit >>> timeit.repeat("for _ in range(100): tim_sort(array)", "from __main__ import tim_sort", number=100000) [2.0640320777893066, 2.0876040458679199, 2.0520210266113281]
By comparing these results, you can assess the relative speed of your "insertion_sort" and "tim_sort" functions and optimize them accordingly.
The above is the detailed content of How Can Python\'s `timeit` Module Help Compare the Performance of Different Sorting Algorithms?. For more information, please follow other related articles on the PHP Chinese website!