Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use timeit module

I understand the concept of what timeit does but I am not sure how to implement it in my code.

How can I compare two functions, say insertion_sort and tim_sort, with timeit?

like image 525
Neemaximo Avatar asked Nov 22 '11 01:11

Neemaximo


People also ask

How do you use %% Timeit in Jupyter?

The “%timeit” is a line magic command in which the code consists of a single line or should be written in the same line for measuring the execution time. In the “%timeit” command, the particular code is specified after the “%timeit” is separated by a space.

What is Timeit?

timeit is used to measure the execution time for the small python code snippets. This module runs the code a million times (by default) to get the most precise value for the code execution time​.

What does Timeit return?

timeit() runs the setup statement one time, then calls the main statement count times. It returns a single floating point value representing the cumulative amount of time spent running the main statement.


1 Answers

If you want to use timeit in an interactive Python session, there are two convenient options:

  1. Use the IPython shell. It features the convenient %timeit special 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 
  2. In a standard Python interpreter, you can access functions and other names you defined earlier during the interactive session by importing them from __main__ in the setup statement:

    >>> 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] 
like image 133
Sven Marnach Avatar answered Sep 23 '22 08:09

Sven Marnach