Profiling and memory use
Profiling measures where a program spends time so you can work on its biggest cost first.
How it works
Use timing to test a specific claim. To compare set membership with list membership, hold the input size and searched value constant, and time the lookup apart from building each collection. Then include the cost of conversion if your real program only performs one lookup.
Walk through an example
If a report takes 100 milliseconds and repeated lookups take 80 of those, improving the lookup is a better starting point than optimizing string formatting.
What to watch for
Measurements can change with input size and workload. Compare repeated runs with realistic inputs and check that changes preserve the result.
Code example
from timeit import timeit
values = set(range(1000))
print(timeit(lambda: 999 in values, number=1000))Check your understanding
Which area is the strongest first candidate for optimization?
See the example and explanation
- Worked example
- Given
Parsing takes 15 ms, lookups 80 ms, formatting 5 ms. - Answer
Lookups.
They account for 80% of the time, so reducing that cost can have the largest effect.