Comparing the Performance Between Loops and Generators
00:00 Comparing the Performance Between Loops and Generators. As always, when measuring performance, you shouldn’t read too much into any one set of results. Instead, design a test for your own code with your own real-world data before you make any important decisions.
00:18 You also need to weigh complexity against readability. Sometimes shaving off a few milliseconds just isn’t worth it. For this test, you’ll want to create a function that can create lists of an arbitrary size with a certain value at a certain position.
The single outlier is the
value argument, and it’s placed at the index provided by the
at_position argument. With this function, you’ll be able to create a large set of lists with the target value at various positions in the list.
timeit is imported, allowing the time taken for the functions to be measured easily. Some constants are declared, allowing the testing intensity and depth to be easily altered in the future.
02:43 Both of these functions are hard-coded to keep things simple for this test. Later in the course, you’ll be creating a reusable function. Now the main loop of the program is created, firstly creating the three lists that will be used for the storage of the the data.
Here the script runs quickly, as
timeit is set to only run each test a hundred times, and there are only fifty tests run for each function. You can then examine the lists that have been created.
You can create a dataset, which may take some time if you increase the
LIST_SIZE and then perform calculations and experiments on the data without having to recalculate it each time. For instance, you can calculate the ratio between the times taken for generators and loops.
Become a Member to join the conversation.