timeit
- Python course
- Expert
- Lesson 37/47
- 5 min
Learn to benchmark with timeit.
What is timeit?
The timeit module measures the execution time of small code snippets. timeit.timeit(expr, number=N) runs expr N times and returns the total time in seconds.
This is the standard tool for comparing two solutions. For example you learn how long sum(range(100)) takes. The number argument sets the repetition count; it is kept high for small expressions. Since the result depends on hardware and load, you use it for comparison rather than printing the value.
The number argument
The number argument sets how many times the measurement repeats. The default is 100000, which is for very short expressions.
For longer expressions you must lower number; otherwise the measurement takes too long. For example timeit.timeit("sum(range(100))", number=100) does 100 repetitions. The result is the total time; for the average you divide by number. For accuracy keep the computer idle; background work can affect the result.
Practice Measure with timeit
Import the module with import timeit. Assign timeit.timeit("sum(range(100))", number=100) to a variable. Then write print("ölçü alındı"). Do not print the measurement result; print only the fixed message.
Starter code
# run the measurement and print a fixed messageSample solution
import timeit
t = timeit.timeit("sum(range(100))", number=100)
print("measurement done")Expected output
ölçü alındı
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Match timeit concepts
| Term | Meaning |
|---|---|
timeit |
Measures time |
number |
Repetition count |
timeit.timeit |
Total time |
expr |
Measured expression |
2 What does timeit.timeit return?
import timeit
t = timeit.timeit('sum(range(10))', number=100)- The repetition count
- Average time
- Total time in seconds Correct answer
- An error
Explanation: timeit.timeit returns the total time in seconds.
3 Complete the timeit call
t = timeit.____("sum(range(100))", number=100)
t = timeit.timeit("sum(range(100))", number=100)
Explanation: timeit.timeit(expr, number=N) does the measurement.