Categories
Python Answers

How to time a code segment for testing performance with Python timeit?

Spread the love

Sometimes, we want to time a code segment for testing performance with Python timeit.

In this article, we’ll look at how to time a code segment for testing performance with Python timeit.

How to time a code segment for testing performance with Python timeit?

To time a code segment for testing performance with Python timeit, we can use the time module.

For instance, we write

import time

t0 = time.time()
foo()
t1 = time.time()

total = t1 - t0

to call time.time to get the current time.

We call foo in between the 2 time calls to get the time at the start and the end of the execution of foo.

And then we get the time elapsed when foo is run with

total = t1 - t0

Conclusion

To time a code segment for testing performance with Python timeit, we can use the time module.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *