3

Linked topic (but not duplicate): Decorator to time specific lines of the code instead of whole method?

I know how decorators are usually used for Python functions.

Is there a similar concept/syntax for single lines of code?

Example: with

def measuretime(lineofcode):
    start = time.time()
    lineofcode()
    print time.time() - start

then

@measuretime
im = Image.open(BytesIO(base64.b64decode(data)))

would be interpreted like

start = time.time()
im = Image.open(BytesIO(base64.b64decode(data)))
print time.time() - start

Notes:

  • I know measuring execution time like this is not optimal, it's better to use timeit, etc. but it's just a random example to show what I'm looking for (decorators for single lines of code)

  • I'm looking for a 1 or 2 lines of code solution (+ definition of the function of course). If the solution takes more than 2 lines of code (i.e. more than something like @measuretime), then it's probably better to give up and just do the normal:

      start = time.time()
      im = Image.open(BytesIO(base64.b64decode(data)))
      print time.time() - start
    
Basj
  • 41,386
  • 99
  • 383
  • 673
  • For test? Use `jupyter` and `%timeit`. – Sraw Jun 28 '18 at 07:56
  • @Sraw I already mentioned `timeit` in the question, and also I'm not using jupyter/ipython but Python in script mode, i.e. `python script.py`. – Basj Jun 28 '18 at 07:58

4 Answers4

6

If you want to do stuff before and after a line of code, a context manager would be appropriate:

from contextlib import contextmanager
import time

@contextmanager
def measuretime():
    start = time.time()
    try:
        yield
    finally:
        print(time.time() - start)

with measuretime():
    do_stuff()
user2357112
  • 260,549
  • 28
  • 431
  • 505
2

No. Decorator is basically a function that takes another function as an argument and returns "decorated" function. @decorator is just a syntactic sugar.

1

No, but the closest thing to your goal would be using a context manager to cover one line of code.

import time

class timer(object):
    def __enter__(self):
        self.start = time.clock()
        return self

    def __exit__(self, *args):
        self.end = time.clock()
        self.interval = self.end - self.start
        print(self.interval)

with timer():
    [i for i in range(100000)]

This outputs the following on my computer:

0.005583688506699192
blhsing
  • 91,368
  • 6
  • 71
  • 106
0

There is no such thing in the language, although you can try looking at jupyter (formerly known as ipython). It has %%timeit shortcut.