Python Code Measure Time
How to measure time of a Python code snippet?
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.
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.
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.
>>> from timeit import timeit >>> timeit('"c" >= "a" and "c" <= "z"') 0.06282545300200582 >>> timeit('"c".isalpha()') 0.06563570606522262
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.
Comments