问题
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
回答1:
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()
回答2:
No. Decorator is basically a function that takes another function as an argument and returns "decorated" function. @decorator is just a syntactic sugar.
回答3:
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
回答4:
There is no such thing in the language, although you can try looking at jupyter
(formerly known as ipython
). It has %%timeit
shortcut.
来源:https://stackoverflow.com/questions/51077539/decorator-like-syntax-for-a-specific-line-of-code