Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
284 views
in Technique[技术] by (71.8m points)

python - 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)
question from:https://stackoverflow.com/questions/65848373/why-calculation-of-execution-time-is-slower-in-timeit-timeit-than-time-time

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...