Difference between revisions of "Python decorators"
Jump to navigation
Jump to search
Rafahsolis (talk | contribs) (Created page with "== Timeit decorator == <syntaxhighlight lang="python3"> import time def timeit(method): def timed(*args, **kw): ts = time.time() result = method(*args, **...") Tag: visualeditor |
Rafahsolis (talk | contribs) Tag: visualeditor |
||
| Line 1: | Line 1: | ||
| − | == Timeit decorator == | + | ==Timeit decorator== |
<syntaxhighlight lang="python3"> | <syntaxhighlight lang="python3"> | ||
import time | import time | ||
| Line 5: | Line 5: | ||
def timeit(method): | def timeit(method): | ||
def timed(*args, **kw): | def timed(*args, **kw): | ||
| − | + | start_time = time.time() | |
result = method(*args, **kw) | result = method(*args, **kw) | ||
| − | + | end_time = time.time() | |
| − | print(f'{method.__name__} {( | + | print(f'{method.__name__} {(end_time - start_time) * 1000} ms') |
return result | return result | ||
return timed | return timed | ||
| + | </syntaxhighlight> | ||
| + | |||
| + | === Usage === | ||
| + | <syntaxhighlight lang="python3"> | ||
| + | @timeit | ||
| + | def test_func(arg1: int)->None: | ||
| + | time.sleep(arg1) | ||
</syntaxhighlight> | </syntaxhighlight> | ||
Latest revision as of 08:46, 14 February 2022
Timeit decorator[edit]
import time
def timeit(method):
def timed(*args, **kw):
start_time = time.time()
result = method(*args, **kw)
end_time = time.time()
print(f'{method.__name__} {(end_time - start_time) * 1000} ms')
return result
return timed
Usage[edit]
@timeit
def test_func(arg1: int)->None:
time.sleep(arg1)