Decorators

In Chapter 5, Saving Time and Memory, I measured the execution time of various expressions. If you recall, I had to initialize a variable to the start time, and subtract it from the current time after execution in order to calculate the elapsed time. I also printed it on the console after each measurement. That was very tedious.

Every time you find yourself repeating things, an alarm bell should go off. Can you put that code in a function and avoid repetition? The answer most of the time is yes, so let's look at an example:

# decorators/time.measure.start.pyfrom time import sleep, timedef f():    sleep(.3)def g():    sleep(.5)t = time()f()print('f took:', time() - t)  # f took: 0.3001396656036377t = time()g()print('g took:', time() - ...

Get Learn Python Programming - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.