Python Python Code Measure Time
We can do it using the timeit module. It has a function called timeit that runs a particular code snippet for N times (one million by default) and gives you the runtime. Today I just used it for a small purpose and thought of writing a note here.
1 | >>> from timeit import timeit<br />>>> timeit('"c" >= "a" and "c" <= "z"')<br />0.06282545300200582<br />>>> timeit('"c".isalpha()')<br />0.06563570606522262<br /> |
Here I compared the performance between two snippets : one uses isalpha() to determine if a (lowercase) character is an alphabet or not, another just compares using operators. There is no noticeable performance difference. Please go through the module doc to get some more ideas of how to use the timeit module, if will often come handy when you quickly want to measure running time of different Python code.