Sometimes when you are coding, you want to know how long it takes for a particular function to run. This topic is known as profiling or performance tuning. Python has a couple of profilers built into its Standard Library, but for small pieces of code, it’s easier to just use Python’s timeit module. Thus, timeit will be the focus of this tutorial. The timeit module uses a platform-specific method to get the most accurate run time. Basically, the timeit module will do a setup once, run the code n number of times and returns the time it took to run. Usually it will output a “best of 3″ score. Oddly enough, the default number of times it runs the code is for 1,000,000 loops. The timeit does timing with time.time() on Linux / Mac and time.clock() on Windows to get the most accurate readings, which is something most people don’t think about.

You can run the timeit module from the command line or by importing it. We will look at both use cases. (more…)