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 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.