Abhijit Kumbhar
Abhijit Kumbhar

Reputation: 961

Why calculation of execution time is slower in timeit.timeit than time.time?

I was just checking the timeit from Pythons official documentation, I have written below program and observed that. Using timeit.timeit it is taking ~12 seconds to execute while the output of time difference (using time.time) it is showing me as 0 seconds. Why so much difference is there.

# CASE 1
# import timeit
# mysetup = """from math import sqrt """
# mycode = """
# lst = []
# for i in range(100):
#     lst.append(sqrt(i))"""
# print(timeit.timeit(setup=mysetup, stmt=mycode))

# CASE 2    
import time
from math import sqrt
t1 = time.time()
lst = []
for i in range(100):
    lst.append(sqrt(i))
t2 = time.time()
print(lst)
print(t2-t1)

Upvotes: 0

Views: 632

Answers (1)

Shehan Jayalath
Shehan Jayalath

Reputation: 704

The timeit module in python helps you to measure execution time of your Python code. This module provides you with much precise measurements compared to the time module as it ignores the background processes running on your system, which might have an impact on your code execution.

Another advantage of using the timeit module vs time is that, by default it performs 1 million executions before providing you with an estimate. This allows you to have statistically relevant measurements for your python code.

timeit try to execute the code snippets a lot of time, and give in output an avarege result.

Upvotes: 1

Related Questions