0 votes
1 view
in Python by (47.8k 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 (107k 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) 

image

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)

image

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

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

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

Related questions

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
0 votes
1 answer
asked Oct 4, 2019 in Python by Sammy (47.8k points)
Welcome to Intellipaat Community. Get your technical queries answered by top developers !


Categories

...