Home > Backend Development > Python Tutorial > How Can Python\'s `timeit` Module Help Compare Algorithm Performance?

How Can Python\'s `timeit` Module Help Compare Algorithm Performance?

Susan Sarandon
Release: 2024-12-03 02:47:11
Original
233 people have browsed it

How Can Python's `timeit` Module Help Compare Algorithm Performance?

Comparing Algorithm Performance with Timeit

The timeit module provides a convenient way to measure and compare the execution time of different functions or code snippets. Here's how you can use this module to compare the performance of your own algorithms, such as "insertion_sort" and "tim_sort":

Interactive Python Session

For an interactive Python session, you can utilize either IPython or the standard Python interpreter.

Using IPython Shell

IPython offers the %timeit function:

def insertion_sort(arr):
    # Your implementation of insertion sort

def tim_sort(arr):
    # Your implementation of tim sort

%timeit for x in range(100): insertion_sort(x)
%timeit for x in range(100): tim_sort(x)
Copy after login

This displays the execution time for each algorithm in microseconds.

Using Standard Python Interpreter

Import your functions from __main__ in the setup statement:

def insertion_sort(arr):
    # Your implementation of insertion sort

def tim_sort(arr):
    # Your implementation of tim sort

import timeit
timeit.repeat("for x in range(100): insertion_sort(x)", "from __main__ import insertion_sort",
              number=100000)
timeit.repeat("for x in range(100): tim_sort(x)", "from __main__ import tim_sort",
              number=100000)
Copy after login

This returns a list of execution times for each algorithm.

The above is the detailed content of How Can Python\'s `timeit` Module Help Compare Algorithm Performance?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template