I understand the concept of what timeit
does but I am not sure how to implement it in my code.
How can I compare two functions, say insertion_sort
and tim_sort
, with timeit
?
I understand the concept of what timeit
does but I am not sure how to implement it in my code.
How can I compare two functions, say insertion_sort
and tim_sort
, with timeit
?
The way timeit works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn't affect the next pass with already sorted data (that, of course, would make the Timsort really shine because it performs best when the data already partially ordered).
Here is an example of how to set up a test for sorting:
Note that the series of statements makes a fresh copy of the unsorted data on every pass.
Also, note the timing technique of running the measurement suite seven times and keeping only the best time -- this can really help reduce measurement distortions due to other processes running on your system.
Those are my tips for using timeit correctly. Hope this helps :-)