Explore Courses Blog Tutorials Interview Questions
0 votes
in Python by (47.6k points)

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?

2 Answers

0 votes
by (106k points)
edited by

The timeit module can be used in an interactive Python session, there are two convenient options:

The first option is to use the IPython shell. It features the convenient %timeit special function.

def f(x):

  return x*x 

%timeit for x in range(100): f(x) 


The second option is to use it in a standard Python interpreter, where 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)


To know more about this you can have a look at the following video tutorial:-

0 votes
by (220 points)
>>> import timeit

>>> setup = '''
import random

s = [random.random() for i in range(1000)]
timsort = list.sort

>>> print min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000))

Related questions

0 votes
1 answer
0 votes
1 answer
+2 votes
2 answers
asked May 23, 2019 in Python by Anvi (10.2k points)
0 votes
1 answer
0 votes
1 answer
Welcome to Intellipaat Community. Get your technical queries answered by top developers!

30.5k questions

32.5k answers


108k users

Browse Categories