Project 18 of 20, for Caitlin
Timing and Retry Decorators
Two decorators for the till on the fruit table at Caitlin's bake sale: one times every call and finds the slow one, one tries the card reader again when it doesn't answer.
Act 2 needs a free account, so your work is saved as you go. Act 1 is open to everyone.
The brief
- CaitlinThe bake sale's got a fruit table now, but the till weighs everything and it's really slow.
- YahyaI timed it at four minutes for two plums, and the queue went right past the next stall.
- CaitlinMy till has a function for everything, and one of them is dawdling. I want to know which.
- YahyaAnd the card reader only answers if you ask it twice, so Caitlin asks it twice, out loud.
- PaulDon't guess which one's slow, measure it, and let the till do the asking twice.
Write a decorator timed that times a function every time it runs, appends (name, seconds) to the list log, and hands back the function's own result. Read the time with clock(): it starts as time.perf_counter, and the checks swap it for a clock that ticks in known steps.
Put @timed on the till's three functions. Then write two helpers for the report:
slowest(entries, count): a list of the names of thecountslowest calls, slowest firstslow_calls(entries, limit): a list of the entries that took longer thanlimitseconds, in the order they happened
Then a second decorator, retry, for the card reader. When the function raises a ConnectionError, it calls it again, up to TRIES calls in all, and hands back the first answer that comes. If the last try fails too, the error comes out. Any other error comes straight out, with no second go. Put @retry on take_card.
Plums: £3.15 Leeks: £1.80 Figs: £1.60 Paid £6.55 by card Slowest: ['look_up_price'] look_up_price took 0.30 s look_up_price took 0.30 s look_up_price took 0.30 s
What you learn
What's in it
- A function is a value
- A function is a value
- Sorting by what matters
- A function on one line
- The slowest call
- Keep some, change each
- Sorting by what matters
- A function that remembers
- A function that remembers
- Wrapping a function
- The @ line
- How Paul would do it
- Fix Riya's version
- Make the decorators
- Ship it