Difference between revisions of "Python decorators"

From RHS Wiki
Jump to navigation Jump to search
(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
 
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):
         ts = time.time()
+
         start_time = time.time()
 
         result = method(*args, **kw)
 
         result = method(*args, **kw)
         te = time.time()
+
         end_time = time.time()
  
         print(f'{method.__name__}  {(te - ts) * 1000} ms')
+
         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)