Created
February 6, 2019 18:50
-
-
Save jtara1/ffa3f503f672c5506fcaaf164b54b837 to your computer and use it in GitHub Desktop.
basic decorator examples
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function timeIt(func) { | |
return async (...args) => { | |
const start = new Date(); | |
const output = await func(...args); | |
console.log(`${func.name} took ${(new Date() - start) / 1000} s`); | |
return output; | |
} | |
} | |
const sleep = async (seconds) => new Promise(resolve => setTimeout(seconds * 1000, resolve)); | |
async function myFunc() { | |
await sleep(2); | |
return true; | |
} | |
myFunc = timeIt(myFunc); | |
// run it | |
(async () => { | |
await myFunc(); | |
})(); |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from time import sleep, time | |
def time_it(func): | |
def run(*args, **kwargs): | |
start = time() | |
output = func(*args, **kwargs) | |
print(f'{func.__name__} took {time() - start} s') | |
return output | |
return run | |
@time_it | |
def my_func(): | |
sleep(2) | |
return True | |
my_func() # run it |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment